java多線程技術之條件變數

來源:互聯網
上載者:User

標籤:

   上一篇講述了並發包下的Lock,Lock可以更好的解決線程同步問題,使之更物件導向,並且ReadWriteLock在處理同步時更強大,那麼同樣,線程間僅僅互斥是不夠的,還需要通訊,本篇的內容是基於上篇之上,使用Lock如何處理線程通訊。

    那麼引入本篇的主角,Condition,Condition 將 Object 監視器方法(wait、notify 和 notifyAll)分解成截然不同的對象,以便通過將這些對象與任意 Lock 實現組合使用,為每個對象提供多個等待 set (wait-set)。其中,Lock 替代了 synchronized 方法和語句的使用,Condition 替代了 Object 監視器方法的使用。下面將之前寫過的一個線程通訊的例子替換成用Condition實現(Java線程(三)),代碼如下:

 

 1 public class ThreadTest2 { 2     public static void main(String[] args) { 3         final Business business = new Business(); 4         new Thread(new Runnable() { 5             @Override 6             public void run() { 7                 threadExecute(business, "sub"); 8             } 9         }).start();10         threadExecute(business, "main");11     }    12     public static void threadExecute(Business business, String threadType) {13         for(int i = 0; i < 100; i++) {14             try {15                 if("main".equals(threadType)) {16                     business.main(i);17                 } else {18                     business.sub(i);19                 }20             } catch (InterruptedException e) {21                 e.printStackTrace();22             }23         }24     }25 }26 class Business {27     private boolean bool = true;28     private Lock lock = new ReentrantLock();29     private Condition condition = lock.newCondition(); 30     public /*synchronized*/ void main(int loop) throws InterruptedException {31         lock.lock();32         try {33             while(bool) {                34                 condition.await();//this.wait();35             }36             for(int i = 0; i < 100; i++) {37                 System.out.println("main thread seq of " + i + ", loop of " + loop);38             }39             bool = true;40             condition.signal();//this.notify();41         } finally {42             lock.unlock();43         }44     }    45     public /*synchronized*/ void sub(int loop) throws InterruptedException {46         lock.lock();47         try {48             while(!bool) {49                 condition.await();//this.wait();50             }51             for(int i = 0; i < 10; i++) {52                 System.out.println("sub thread seq of " + i + ", loop of " + loop);53             }54             bool = false;55             condition.signal();//this.notify();56         } finally {57             lock.unlock();58         }59     }60 }

      在Condition中,用await()替換wait(),用signal()替換notify(),用signalAll()替換notifyAll(),傳統線程的通訊方式,Condition都可以實現,這裡注意,Condition是被綁定到Lock上的,要建立一個Lock的Condition必須用newCondition()方法。

 

        這樣看來,Condition和傳統的線程通訊沒什麼區別,Condition的強大之處在於它可以為多個線程間建立不同的Condition,下面引入API中的一段代碼,加以說明。

 

 1 class BoundedBuffer { 2    final Lock lock = new ReentrantLock();//鎖對象 3    final Condition notFull  = lock.newCondition();//寫線程條件  4    final Condition notEmpty = lock.newCondition();//讀線程條件  5  6    final Object[] items = new Object[100];//緩衝隊列 7    int putptr/*寫索引*/, takeptr/*讀索引*/, count/*隊列中存在的資料個數*/; 8  9    public void put(Object x) throws InterruptedException {10      lock.lock();11      try {12        while (count == items.length)//如果隊列滿了 13          notFull.await();//阻塞寫線程14        items[putptr] = x;//賦值 15        if (++putptr == items.length) putptr = 0;//如果寫索引寫到隊列的最後一個位置了,那麼置為016        ++count;//個數++17        notEmpty.signal();//喚醒讀線程18      } finally {19        lock.unlock();20      }21    }22 23    public Object take() throws InterruptedException {24      lock.lock();25      try {26        while (count == 0)//如果隊列為空白27          notEmpty.await();//阻塞讀線程28        Object x = items[takeptr];//取值 29        if (++takeptr == items.length) takeptr = 0;//如果讀索引讀到隊列的最後一個位置了,那麼置為030        --count;//個數--31        notFull.signal();//喚醒寫線程32        return x;33      } finally {34        lock.unlock();35      }36    } 37  }

 

        這是一個處於多線程工作環境下的緩衝區,緩衝區提供了兩個方法,put和take,put是存資料,take是取資料,內部有個緩衝隊列,具體變數和方法說明見代碼,這個緩衝區類實現的功能:有多個線程往裡面存資料和從裡面取資料,其緩衝隊列(先進先出後進後出)能緩衝的最大數值是100,多個線程間是互斥的,當緩衝隊列中儲存的值達到100時,將寫線程阻塞,並喚醒讀線程,當緩衝隊列中儲存的值為0時,將讀線程阻塞,並喚醒寫線程,下面分析一下代碼的執行過程:

 

        1. 一個寫線程執行,調用put方法;

        2. 判斷count是否為100,顯然沒有100;

        3. 繼續執行,存入值;

        4. 判斷當前寫入的索引位置++後,是否和100相等,相等將寫入索引值變為0,並將count+1;

        5. 僅喚醒讀線程阻塞隊列中的一個;

        6. 一個讀線程執行,調用take方法;

        7. ……

        8. 僅喚醒寫線程阻塞隊列中的一個。

        本文來自:高爽|Coder,原文地址:http://blog.csdn.net/ghsau/article/details/7481142,轉載請註明。

java多線程技術之條件變數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.