并发包中关于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个线程都完成之后才会执行.

 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值