1. 程式人生 > >8、JUC--Condition 控制線程通信

8、JUC--Condition 控制線程通信

lock 性問題 out oid + - stack info code 需要

Condition

? Condition 接口描述了可能會與鎖有關聯的條件變量。這些變量在用
  法上與使用 Object.wait 訪問的隱式監視器類似,但提供了更強大的
  功能。需要特別指出的是,單個 Lock 可能與多個 Condition 對象關
  聯。為了避免兼容性問題,Condition 方法的名稱與對應的 Object 版
  本中的不同。
? 在 Condition 對象中,與 wait、notify 和 notifyAll 方法對應的分別是
  await、signal 和 signalAll。
? Condition 實例實質上被綁定到一個鎖上。要為特定 Lock 實例獲得
  Condition 實例,請使用其 newCondition() 方法

使用Lock鎖進行控制線程安全

繼上一個工程的項目更改:

class Clerk1{
    private int product =0;
    
    //Lock鎖
    private Lock lock = new ReentrantLock();
    //獲取Condition對象
    private Condition condition = lock.newCondition();
    //進貨
    public  void get(){
        //上鎖
        lock.lock();
        
try { while(product >=1){ System.out.println("產品已滿!"); try { //this.wait(); condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } System.
out.println(Thread.currentThread().getName()+":"+ ++product); //this.notifyAll(); condition.signalAll(); } finally { //解鎖 lock.unlock(); } } //賣貨 public void sale(){ //上鎖 lock.lock(); try { while(product <=0){ System.out.println("產品賣完"); try { //this.wait(); condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+":"+ --product); //this.notifyAll(); condition.signalAll(); } finally { lock.unlock(); } } }

此時運行之後的結果:

技術分享圖片

8、JUC--Condition 控制線程通信