標籤:exce 參考 語句 pre items lan style ant empty
Condition 將 Object 監視器方法(wait、notify 和 notifyAll)分解成截然不同的對象,以便通過將這些對象與任意 Lock 實現組合使用,為每個對象提供多個等待 set(wait-set)。其中,Lock 替代了 synchronized 方法和語句的使用,Condition 替代了 Object 監視器方法的使用。今天我們就通過執行個體來學習一個Condition的用法。
多線程中Condition的簡單使用
一、關於裝水取水的例子
- BoundedBuffer:沒有水時可以裝水但不能取水,當水滿的時候不能裝水但能取水。
import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;class BoundedBuffer { final Lock lock = new ReentrantLock(); final Condition notFull = lock.newCondition(); final Condition notEmpty = lock.newCondition(); final String[] items = new String[10]; int putptr, takeptr, count; public void put(String x) throws InterruptedException { lock.lock(); try { while (count == items.length) notFull.await(); items[putptr] = x; if (++putptr == items.length) putptr = 0; ++count; notEmpty.signal(); } finally { lock.unlock(); } } public String take() throws InterruptedException { lock.lock(); try { while (count == 0) notEmpty.await(); String x = items[takeptr]; if (++takeptr == items.length) takeptr = 0; --count; notFull.signal(); return x; } finally { lock.unlock(); } }}
- ConditionTest1:開啟兩個線程,分別20次的取水和裝水操作。
public class ConditionTest1 { public static void main(String[] args) throws Exception { final BoundedBuffer boundedBuffer = new BoundedBuffer(); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 20; i++) { try { boundedBuffer.take(); System.out.print("t" + i + " "); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 20; i++) { try { boundedBuffer.put("string" + i); System.out.print("p" + i + " "); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); }}
啟動並執行結果如下:不固定
p0 p1 p2 p3 p4 p5 p6 p7 p8 p9 t0 p10 t1 p11 t2 p12 t3 p13 t4 p14 t5 p15 t6 p16 t7 p17 t8 p18 t9 p19 t10 t11 t12 t13 t14 t15 t16 t17 t18 t19
友情連結
- 比較好的參考部落格:http://www.cnblogs.com/lcngu/p/5208465.html
java進階---->Thread之Condition的使用