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

 

你可能感兴趣的:(java,基础)