CountDownLatch的用法/等待多线程执行结果

在前面一篇博文http://guoba6688-sina-com.iteye.com/blog/724536中提出如何更方便的等待多线程执行结果,该篇博文的做法是

//等待线程执行完毕   
        while(threadPool.getActiveCount() > 0){   
            try{   
                Thread.sleep(1000);   
            }catch(Exception e){   
                e.printStackTrace();   
            }   
        }   

 

今天发现java类库中的CountDownLatch可以很方便的完成这个工作

 

CountDownLatch的原理时

1、先设一个线程数,通过构造函数。

2、启动线程后,调用await()方法等待内部保持的线程数归零

3、每个线程在完成后调用countDown(),将活动的线程数减1

4、当活动线程数归零后,执行下面的代码

 

 

附上代码

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 
 * CountDownLatch  的用法
 *
 * @author 锅巴
 * @version 1.0 2010-8-9
 */
public class Main {

    private ExecutorService pool;
    private int threadCount = 10;
    private CountDownLatch countDownLatch;
    
    public static void main(String[] args) throws InterruptedException {
        
        Main main = new Main();
        main.execute();
       
        System.out.println("Main is end ");
        
//        System.exit(0);
    }
    
    public Main(){
        threadCount = 10;
        pool = Executors.newFixedThreadPool(threadCount);
        //初始化线程数
        countDownLatch = new CountDownLatch(threadCount);
    }
    
    public void execute() throws InterruptedException{
        for(int i=0; i<threadCount; i++){
            pool.execute(new Handler(10,countDownLatch));
        }
        pool.shutdown();
        //等待线程执行完成
        //实现上是等待count变成0
        countDownLatch.await();
       
    }
    
    
    class Handler implements Runnable {
       
        private int count;
        
        private CountDownLatch countDownLatch;

        public Handler(int count,CountDownLatch countDownLatch) {
            this.count = count;
            this.countDownLatch = countDownLatch;
        }

        public void run() {
            // read and service request
            for(int i=0; i<count; i++){
                System.out.println(Thread.currentThread().getName() + " : " + i);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            //当本线程完成就减1
            countDownLatch.countDown();
        }
    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值