Java-JUC(九):使用Lock替換synchronized,使用Condition的await,singal,singalall替換object的wait,notify,notifyall實現線程間的通信
阿新 • • 發佈:2018-04-30
可能 AR purchase name ati for rac 需要 條件變量
Condition:
- condition接口描述了可能會與鎖有關的條件變量。這些用法上與使用object.wait訪問隱式監視器類似,但提供了更強大的功能。需要特別指出的是,單個lock可能與多個Condition對象關聯。為了避免兼容性問題,Condition方法的名稱與對應的objec版本中的不同。
- 在condition對象中,與wait、notify、notifyall方法對應的分別是await、singal、signalAll
- Condition實例實質上被綁定到一個鎖上。要為特定Lock實例獲得Condition實例,請使用其newCondition()方法。
使用Lock替換Synchronized,使用Condition替換Ojbect實現線程間的通信
例子如下:
package com.dx.juc.test; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class LockAndConditionTest { public static void main(String[] args) { Clerk clerk = new Clerk(); Productor productor= new Productor(clerk); Consumer consumer = new Consumer(clerk); new Thread(productor, "Productor-A").start(); new Thread(consumer, "Consumer-A").start(); new Thread(productor, "Productor-B").start(); new Thread(consumer, "Consumer-B").start(); } }/** * 店員 */ class Clerk { private int product = 0; private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); /** * 進貨 */ public void purchase() { lock.lock(); try { while (product >= 1) { System.out.println(Thread.currentThread().getName() + ":" + "產品已滿。。。"); try { condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + ":" + ++product); condition.signalAll(); } finally { lock.unlock(); } } /** * 賣貨 */ public void sell() { lock.lock(); try { while (product <= 0) { System.out.println(Thread.currentThread().getName() + ":" + "產品缺貨。。。"); try { condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + ":" + --product); condition.signalAll(); } finally { lock.unlock(); } } } /** * 生產者 不斷的生產產品給店員 */ class Productor implements Runnable { private Clerk clerk; public Productor(Clerk clerk) { this.clerk = clerk; } public void run() { for (int i = 0; i < 2; i++) { clerk.purchase(); } } } /** * 消費者 不斷的從店員那裏消費產品 */ class Consumer implements Runnable { private Clerk clerk; public Consumer(Clerk clerk) { this.clerk = clerk; } public void run() { for (int i = 0; i < 2; i++) { clerk.sell(); } } }
Java-JUC(九):使用Lock替換synchronized,使用Condition的await,singal,singalall替換object的wait,notify,notifyall實現線程間的通信