`
影非弦
  • 浏览: 50719 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

    博客分类:
  • java
阅读更多

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

代码如下:

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();
		}
	}
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics