1. 程式人生 > >併發包中關於CountDownLatch類的使用

併發包中關於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個執行緒都完成之後才會執行.