CountDownLatch浅谈

CountDownLatch是一个同步计数器,从jdk1.5加入concurrent包时引入的

以下是官方文档的描述:
A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
一个同步工具————允许一个或多个线程等待直到其他一些线程的操作完成

我们通过一个例子来解释下这句话:

public class countdownlatch {
    private static final int THREAD_NUM = 5;
    
    public static class Worker implements Runnable{
        CountDownLatch cdl;
        public Worker(CountDownLatch c){
            this.cdl = c;
        }
        @Override
        public void run() {
            System.out.println("ID:"+Thread.currentThread().getId()+" Worker's waiting");
            cdl.countDown();//每个Worker线程执行此句都会将同步计数器中的数减一,并且这句话并不会阻塞该线程
            System.out.println("ID:"+Thread.currentThread().getId()+" Working");
        }
    }
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch cdl = new CountDownLatch(THREAD_NUM);
        for (int i = 0; i < THREAD_NUM; i++) {
            new Thread(new Worker(cdl)).start();
        }
        cdl.await();//主线程被同步工具countdownlatch挂起在此处,当计数器中的值为0时,主线程被唤醒,开始执行后面的代码
        System.out.println("主线程开始工作");
    }
}



运行结果:
ID:9 Worker's waiting
ID:9 Working
ID:10 Worker's waiting
ID:10 Working
ID:12 Worker's waiting
ID:12 Working
ID:13 Worker's waiting
ID:13 Working
ID:11 Worker's waiting
主线程开始工作
ID:11 Working

主线程是否被唤醒,只关心计数器是否被减到0

posted @ 2017-05-06 12:09  暗夜心慌方  阅读(106)  评论(0编辑  收藏  举报