标签:lock nal java 事件 util 工作 test void 1.5
条件变量Condition提供了一种基于ReentrantLock的事件等待和通知的机制,并且可以监控任意指定的条件,在条件不满足时等待条件满足,其它线程在条件满足时可以通知等待条件的线程,从而唤醒等待中的线程。
下面的代码实现了两件工作分别由两个线程轮流不断执行的效果。
package com.test.concurrence; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ConditionTest { static class Worker { public void work(int who ,int next, int count){ //获取锁 lock.lock(); try { //等待条件成立:turn等于who while(who != turn){ try { condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } //条件已满足,开始做要做的事情 for(int i=0;i<count;i++){ System.out.println( who + " : running " + i + " / " + count ); } //暂停1秒。 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //改变条件。 turn = next; //通知下一个工人开始工作。 condition.signal(); }finally{ //释放锁。 lock.unlock(); } } //所使用的锁。 private Lock lock = new ReentrantLock(); //条件变量。 private Condition condition = lock.newCondition(); //条件要监控的变量。 private volatile int turn = 0; } public static void main(String[] args) { final int WORKER_A = 0; final int WORKER_B = 1; final int COUNT = 10; final Worker worker = new Worker(); new Thread( new Runnable(){ @Override public void run() { while(true){ worker.work( WORKER_A, WORKER_B, COUNT); } } }).start(); new Thread( new Runnable(){ @Override public void run() { while(true){ worker.work( WORKER_B, WORKER_A, COUNT); } } }).start(); } }
运行结果如下所示:
0 : running 0 / 10
0 : running 1 / 10
0 : running 2 / 10
0 : running 3 / 10
0 : running 4 / 10
0 : running 5 / 10
0 : running 6 / 10
0 : running 7 / 10
0 : running 8 / 10
0 : running 9 / 10
1 : running 0 / 10
1 : running 1 / 10
1 : running 2 / 10
1 : running 3 / 10
1 : running 4 / 10
1 : running 5 / 10
1 : running 6 / 10
1 : running 7 / 10
1 : running 8 / 10
1 : running 9 / 10
0 : running 0 / 10
0 : running 1 / 10
0 : running 2 / 10
0 : running 3 / 10
0 : running 4 / 10
0 : running 5 / 10
0 : running 6 / 10
0 : running 7 / 10
0 : running 8 / 10
0 : running 9 / 10
标签:lock nal java 事件 util 工作 test void 1.5
原文地址:http://www.cnblogs.com/coe2coe/p/6613606.html