傳統線程間通訊是使用wait和notify,可是這種智能實現一路等待,使用condition以後能夠實現多路等待
java
用condition實現緩衝區oop
class BoundedBuffer { final Lock lock = new ReentrantLock();//實例化一個鎖對象 final Condition notFull = lock.newCondition(); //實例化兩個condition final Condition notEmpty = lock.newCondition(); final Object[] items = new Object[100];//初始化一個長度爲100的隊列 int putptr, takeptr, count; public void put(Object x) throws InterruptedException { lock.lock();//獲取鎖 try { while (count == items.length) notFull.await();//當計數器count等於隊列的長度時,不能在插入,所以等待 items[putptr] = x; //將對象放入putptr索引處 if (++putptr == items.length) putptr = 0;//當索引長度等於隊列長度時,將putptr置爲0 //緣由是,不能越界插入 ++count;//沒放入一個對象就將計數器加1 notEmpty.signal();//一旦插入就喚醒取數據線程 } finally { lock.unlock();//最後釋放鎖 } } public Object take() throws InterruptedException { lock.lock();//獲取鎖 try { while (count == 0) //若是計數器等於0那麼等待 notEmpty.await(); Object x = items[takeptr]; //取得takeptr索引處對象 if (++takeptr == items.length) takeptr = 0;//當takeptr達到隊列長度時,從零開始取 --count;//每取一個講計數器減1 notFull.signal();//枚取走一個就喚醒存線程 return x; } finally { lock.unlock();//釋放鎖 } } }
2.同時用其可使多路線程實現等待:this
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ConditionCommunication { /** * @param args */ public static void main(String[] args) { final Business business = new Business(); new Thread(new Runnable(){ public void run() { for(int i=0; i<50; i++){ business.sub2(i); } } }).start(); new Thread(new Runnable(){ public void run() { for(int i=0; i<50; i++){ business.sub3(i); } } }).start(); new Thread(new Runnable(){ public void run() { for(int i=0; i<50; i++){ business.main(i); } } }).start(); } static class Business{ private int shouldSub = 1; private Lock lock = new ReentrantLock(); Condition condition1 = lock.newCondition(); Condition condition2 = lock.newCondition(); Condition condition3 = lock.newCondition(); public void sub2(int i){ try{ lock.lock(); while(shouldSub != 2){ try { // this.wait(); condition2.await(); } catch (Exception e) { e.printStackTrace(); } } for(int j=1; j<=10; j++){ System.out.println("sub2 thread sequence is " + j + " loop of " + i); } shouldSub = 3; // this.notify(); condition3.signal(); }finally{ lock.unlock(); } } public void sub3(int i){ try{ lock.lock(); while(shouldSub != 3){ try { // this.wait(); condition3.await(); } catch (Exception e) { e.printStackTrace(); } } for(int j=1; j<=20; j++){ System.out.println("sub3 thread sequence is " + j + " loop of " + i); } shouldSub = 1; // this.notify(); condition1.signal(); }finally{ lock.unlock(); } } public void main(int i){ try{ lock.lock(); while(shouldSub != 1){ try { // this.wait(); condition1.await(); } catch (Exception e) { e.printStackTrace(); } } for(int j=1; j<=100; j++){ System.out.println("main thread sequence is " + j + " loop of " + i); } shouldSub = 2; // this.notify(); condition2.signal(); }finally{ lock.unlock(); } } } }