并发编程 - 倒数锁CountDownLatch

CountDownLatch 倒数锁,顾名思义,需要给定一个初始值,每次调用计数减一,计数到达零之前,线程将一直受阻塞,计数到零之后,会释放所有等待的线程。

业务场景:主线程需要5个并发的初始化操作,5个线程全部执行完毕,主线程开始执行。

/**
 * @author ChenSS on 2018年2月3日
 */
public class Test {
    private static CountDownLatch latch = new CountDownLatch(5);
    
    public static void main(String[] args) throws InterruptedException {
        int count = 5;
        while (count-- > 0) {
            final int n = count;
            new Thread(() -> {
                try {
                    Thread.sleep(3000 + RandomUtils.nextLong(3000));
                    System.out.println("完成第" + n + "个步骤");
                    //完成一个初始化,倒计时一次(5--)
                    latch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
        // 主线程进入等待,在倒计时为零的时候继续执行
        latch.await();
        // 引用置空
        latch = null;
        System.out.println("五个初始化操作成功,进行别的操作!");
        
    }
}

posted on 2018-02-03 08:33  疯狂的妞妞  阅读(112)  评论(0编辑  收藏  举报

导航