黑马程序员---Lock和Condition

本文介绍了一种使用Lock和Condition实现多线程同步的方法,并通过实例展示了如何创建一个可扩展的多线程类来自动管理多个线程的循环执行。

---------------------- android培训java培训、期待与您交流! ----------------------

感觉Lock和Condition比synchronized要好理解一点
说不定也是学完synchronized之后的感觉...

功能是强大许多

张老师说那个主线程子线程交替的面试题

还可以拓展一下 写成3个线程的

于是我就再拓展了一下

写了一个DoSomething类
可以传递3个参数
1.实现了Runnable的对象
2.线程数量
3.需要loop的次数
然后就会自动建立线程循环按顺序
调用Runnable对象的run方法


import java.util.concurrent.locks.*;

class DoSomething{
	private boolean[] run=null;					//记录各个线程可否运行的boolean
	private ReentrantLock lock=null;			
	private Condition[] condition=null;			//各个线程的condition
	private Thread[] thread=null;				//线程数组
	private int count=0;						
	private int current=0;						//当前线程的脚标号
	private Runnable task=null;
	private int loop=0;							//剩余循环次数
	public DoSomething(Runnable task,int count,int loop){
		this.count=count;
		this.task=task;
		this.loop=loop;
		lock=new ReentrantLock();
		run=new boolean[count];
		condition=new Condition[count];
		thread=new Thread[count];
		for(int i=0;i<count;i++){
			condition[i]=lock.newCondition();
			run[i]=false;
			thread[i]=new Thread(new Task(i));
		}
		run[0]=true;							//从第一个线程开始
		for(int i=0;i<count;i++)
			thread[i].start();
	}
	class Task implements Runnable{
		private int num;						//记录线程的脚标号
		public Task(int num){
			this.num=num;
		}
		public void run(){
			while(loop-->0){
				lock.lock();
				while(!run[num]){
					try{
						condition[num].await();		//线程对应的condition的await
					}catch(InterruptedException e){
						e.printStackTrace();
					}
				}
				System.out.println(Thread.currentThread().getName() +"start");
				task.run();
				System.out.println(Thread.currentThread().getName() +"end\r\n");
				run[current]=false;					//当前线程等待
				if(++current==count)current=0;		//下一个线程boolean设为true,唤醒
				run[current]=true;			//
				condition[current].signal();		//
				lock.unlock();
			}
		}
	}
}

class ConditionTest{
	public static void main(String[] args){
		new DoSomething(new something(),3,10);
	}
	
	static class something implements Runnable{
		public void run(){
			for(int i=0;i<20;i++)
				System.out.print(i+" ");
			System.out.println();
		}
	}
}



---------------------- android培训java培训、期待与您交流! ----------------------
详细请查看: http://edu.csdn.net/heima
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值