java多線程-Condition,多線程-condition

來源:互聯網
上載者:User

java多線程-Condition,多線程-condition

Condition 將 Object 監視器方法(wait、notify 和 notifyAll)分解成截然不同的對象,以便通過將這些對象與任意 Lock 實現組合使用,為每個對象提供多個等待 set(wait-set)。其中,Lock 替代了 synchronized 方法和語句的使用,Condition 替代了 Object 監視器方法的使用。

先看一個關於Condition使用的簡單一實例:

 1 public class ConditionTest { 2     public static void main(String[] args) { 3         final Lock lock = new ReentrantLock(); 4         final Condition condition = lock.newCondition(); 5          6         Thread thread1 = new Thread(new Runnable() { 7             @Override 8             public void run() { 9                 try {10                     lock.lock();11                     System.out.println("我需要等一個訊號"+this);12                     condition.await();13                     System.out.println("我拿到一個訊號"+this);14                 } catch (Exception e) {15                     // TODO: handle exception16                 } finally{17                     lock.unlock();18                 }19                 20                 21             }22         }, "thread1");23         thread1.start();24         Thread thread2 = new Thread(new Runnable() {25             @Override26             public void run() {27                 try {28                     lock.lock();29                     System.out.println("我拿到了鎖");30                     Thread.sleep(500);31                     System.out.println("我發出一個訊號");32                     condition.signal();33                 } catch (Exception e) {34                     // TODO: handle exception35                 } finally{36                     lock.unlock();37                 }38                 39                 40             }41         }, "thread2");42         thread2.start();43     }44 }

運行結果:

1 我需要等一個訊號com.luchao.traditionalthread.ConditionTest$1@10bc3c92 我拿到了鎖3 我發出一個訊號4 我拿到一個訊號com.luchao.traditionalthread.ConditionTest$1@10bc3c9View Code

可以看到,Condition的執行方式,是當線上程1中調用await方法後,線程1將釋放鎖,並且將自己沉睡,等待喚醒,線程2擷取到鎖後,開始做事,完畢後,調用Condition的signal方法,喚醒線程1,線程1恢複執行。

以上說明Condition是一個多線程間協調通訊的工具類,使得某個,或者某些線程一起等待某個條件(Condition),只有當該條件具備( signal 或者 signalAll方法被帶調用)時 ,這些等待線程才會被喚醒,從而重新爭奪鎖。

Condition與傳統線程通訊有些類似,它的使用更廣,可以將多個線程進行通訊,以完成更加複雜的通訊。

用Condition替換傳統線程通訊,在前面的傳統有一個子線程和主線程交替運行50次的執行個體,使用Condition也可以完成。

代碼如下:

 1 public class ConditionCommuniction { 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                 for (int i = 0; i < 50; i++) { 8                     business.sub(i); 9                 }10             }11         }).start();12         for (int i = 0; i < 50; i++) {13             business.main(i);14         }15     }16     17     18     static class Business{19         private Lock lock = new ReentrantLock();20         private boolean isMain = true;21         private Condition condition = lock.newCondition();22         public void main(int i){23             lock.lock();24             try {25                 while(!isMain){26                     condition.await();27                 }28                 for (int j = 0; j < 100; j++) {29                     System.out.println("main is looping  :" + j +" in " + i);30                 }31                 isMain = false;32                 condition.signal();33             } catch (Exception e) {34                 // TODO: handle exception35             } finally{36                 lock.unlock();37             }38         }39         public void sub(int i){40             lock.lock();41             try {42                 while(isMain){43                     condition.await();44                 }45                 for (int j = 0; j < 10; j++) {46                     System.out.println("sub is looping  :" + j +" in " + i);47                 }48                 isMain = true;49                 condition.signal();50             } catch (Exception e) {51                 // TODO: handle exception52             } finally{53                 lock.unlock();54             }55         }56     }57 }

  在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;//如果寫索引寫到隊列的最後一個位置了,那麼置為0  16        ++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;//如果讀索引讀到隊列的最後一個位置了,那麼置為0  30        --count;//個數--  31        notFull.signal();//喚醒寫線程  32        return x;  33      } finally {  34        lock.unlock();  35      }  36    }   37  }  

  這就是多個Condition的強大之處,假設緩衝隊列中已經存滿,那麼阻塞的肯定是寫線程,喚醒的肯定是讀線程,相反,阻塞的肯定是讀線程,喚醒的肯定是寫線程,那麼假設只有一個Condition會有什麼效果呢,緩衝隊列中已經存滿,這個Lock不知道喚醒的是讀線程還是寫線程了,如果喚醒的是讀線程,皆大歡喜,如果喚醒的是寫線程,那麼線程剛被喚醒,又被阻塞了,這時又去喚醒,這樣就浪費了很多時間。

  將上面主線程和子線程交替啟動並執行程式進行擴充,三個線程交替運行,代碼如下:

 1 public class ThreeConditionCommunication { 2     public static void main(String[] args) { 3         final Business business = new Business(); 4         new Thread(new Runnable() { 5              6             @Override 7             public void run() { 8                 for (int i = 0; i < 50; i++) { 9                     business.sub1(i);10                 }11             }12         }).start();13         new Thread(new Runnable() {14             15             @Override16             public void run() {17                 for (int i = 0; i < 50; i++) {18                     business.sub2(i);19                 }20             }21         }).start();22         for (int i = 0; i < 50; i++) {23             business.main(i);24         }25     }26     static class Business{27         Lock lock = new ReentrantLock();28         Condition main = lock.newCondition();29         Condition sub1 = lock.newCondition();30         Condition sub2 = lock.newCondition();31         int runNum = 1;32         33         public void main(int i){34             lock.lock();35             try {36                 while(runNum!=1){37                     main.await();//主線程等待38                 }39                 for (int j = 0; j < 100; j++) {40                     System.out.println("main is looping of "+j+" in "+i);41                 }42                 runNum = 2;43                 sub1.signal();//喚醒子線程144             } catch (Exception e) {45                 // TODO: handle exception46             } finally{47                 lock.unlock();48             }49         }50         public void sub1(int i){51             lock.lock();52             try {53                 while(runNum!=2){54                     sub1.await();//子線程1等待55                 }56                 for (int j = 0; j < 10; j++) {57                     System.out.println("sub1 is looping of "+j+" in "+i);58                 }59                 runNum = 3;60                 sub2.signal();//喚醒子線程261             } catch (Exception e) {62                 // TODO: handle exception63             } finally{64                 lock.unlock();65             }66         }67         public void sub2(int i){68             lock.lock();69             try {70                 while(runNum!=3){71                     sub2.await();//子線程2等待72                 }73                 for (int j = 0; j < 20; j++) {74                     System.out.println("sub2 is looping of "+j+" in "+i);75                 }76                 runNum = 1;77                 main.signal();//喚醒主線程78             } catch (Exception e) {79                 // TODO: handle exception80             } finally{81                 lock.unlock();82             }83         }84     }85 }

由此可見,Condition在多線程通訊的強大作用,可以大大提高程式效率。

聯繫我們

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