閱讀890 返回首頁    go 阿裏雲 go 技術社區[雲棲]


並發包中關於CountDownLatch類的使用

一個非常有用的類,CountDownLatch, 可以用來在一個線程中等待多個線程完成任務的類;
通常的使用場景是,某個主線程接到一個任務,起了n個子線程去完成,但是主線程需要等待這n個子線程都完成任務了以後才開始執行某個操作;

測試代碼如下:

package test;

import java.util.concurrent.CountDownLatch;

public class TestThread {

 /**
  *
  * @author Administrator/2012-3-1/上午09:19:02
  */
 public static void main(String[] args) {

  TestThread t=new TestThread();
  t.demoCountDown();

 }
 
 
 public void demoCountDown()  
 {  
     int count = 10;  
  
     final CountDownLatch l = new CountDownLatch(count);  
     for(int i = 0; i < count; ++i)  
     {  
         final int index = i;  
         new Thread(new Runnable() {  
  
             @Override 
             public void run() {  
  
                 try {  
                     Thread.currentThread().sleep(20 * 1000);  
                 } catch (InterruptedException e) {  
  
                     e.printStackTrace();  
                 }  
  
                 System.out.println("thread " + index + " has finished...");  
  
                 l.countDown();  
  
             }  
         }).start();  
     }  
  
     try {  
         l.await();  
     } catch (InterruptedException e) {  
  
         e.printStackTrace();  
     }  
  
     System.out.println("now all threads have finished");  
  
 } 


}

 

 

運行結果:

 

 

thread 1 has finished...
thread 3 has finished...
thread 0 has finished...
thread 7 has finished...
thread 4 has finished...
thread 9 has finished...
thread 8 has finished...
thread 2 has finished...
thread 6 has finished...
thread 5 has finished...
now all threads have finished

 

前麵10個線程的執行完成順序會變化,但是最後一句始終會等待前麵10個線程都完成之後才會執行.

 


 

最後更新:2017-04-02 22:16:29

  上一篇:go SYSTEM.GC FINALIZE小小的注釋
  下一篇:go 動態添加刪除表格行的js腳本