Java线程学习笔记一-----Lock与Condition实现线程同步通信_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java线程学习笔记一-----Lock与Condition实现线程同步通信

Java线程学习笔记一-----Lock与Condition实现线程同步通信

 2014/11/6 18:18:26  影非弦  程序员俱乐部  我要评论(0)
  • 摘要:小例子:创建三个线程A,B,C,A线程循环10次,接着B线程再循环10次,然后C线程再循环10次,然后A线程又循环10次,如此循环往复50次。代码如下:publicclassThreeThreadCommunication{publicstaticvoidmain(String[]args){finalBusinessbusiness=newBusiness();newThread(newRunnable(){@Overridepublicvoidrun(){for(inti=1;i<
  • 标签:笔记 实现 学习 Java 学习笔记 线程 同步

例子:创建三个线程A,B,C, A线程循环10次,接着B线程再循环10次,然后C线程再循环10次,然后A线程又循环10次,如此循环往复50次。

代码如下:

class="java">public class ThreeThreadCommunication {

	public static void main(String[] args) {
		final Business business = new Business();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				for(int i = 1; i <= 50; i++){
					business.sub1(i);
				}
			}
		}).start();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				for(int i = 1; i <= 50; i++){
					business.sub2(i);
				}
			}
		}).start();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				for(int i = 1; i <= 50; i++){
					business.sub3(i);
				}
			}
		}).start();
	}
}

class Business{
	Lock lock = new ReentrantLock();
	Condition condition1 = lock.newCondition();
	Condition condition2 = lock.newCondition();
	Condition condition3 = lock.newCondition();
	private int flag = 1;
	
	public void sub1(int j){
		lock.lock();
		try{
			while(flag != 1){
				condition1.await();
			}
			
			for(int i = 1;i <= 10;i++){
				System.out.println("sub1 thread sequence of " + i + ",loop of " + j);
			}
			flag = 2;
			condition2.signal();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			lock.unlock();
		}
	}
	
	public void sub2(int j){
		lock.lock();
		try{
			while(flag != 2){
				condition2.await();
			}
			
			for(int i = 1; i <= 10; i++){
				System.out.println("sub2 thread sequence of " + i + ",loop of " + j);
			}
			flag = 3;
			condition3.signal();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			lock.unlock();
		}
	}
	
	public void sub3(int j){
		lock.lock();
		try{
			while(flag != 3){
				condition3.await();
			}
			
			for (int i = 1; i <= 10; i++) {
				System.out.println("sub3 thread sequence of " + i + ",loop of " + j);
			}
			flag = 1;
			condition1.signal();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			lock.unlock();
		}
	}
}

?

?

发表评论
用户名: 匿名