標籤:lock nal java 事件 util 工作 test void 1.5
1.1.1. 條件變數應用之等待通知
條件變數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(){@Overridepublic void run() {while(true){worker.work( WORKER_A, WORKER_B, COUNT);}}}).start(); new Thread( new Runnable(){@Overridepublic 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
Java並發程式設計(16)並發鎖之條件變數