Java並發程式設計(16)並發鎖之條件變數

來源:互聯網
上載者:User

標籤: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)並發鎖之條件變數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.