Java Concurrent: CountDownLatch

Javajuc大约 1870 字

作用

允许一个或多个线程等待,直到其他线程的一组操作完成后,再完成自身线程中暂停后的后续操作。

倒计时:到0(设置倒数几秒)就执行下一步。

构造函数

count:门闩的数量,门闩的数量为0时,CountDownLatch 所在线程继续执行后续操作。

线程可以继续执行后续操作前必须要调用countDown()方法的次数。

public CountDownLatch(int count) {
    if (count < 0) throw new IllegalArgumentException("count < 0");
    this.sync = new Sync(count);
}

countDown()方法

使门闩数量减1。当门闩数量小于等于0时,该方法不做任何事。

await()方法

使 CountDownLatch 所在线程暂停,直到 count 为 0。

案例

public class CountDownLatchDemo {

    public static void main(String[] args) throws Exception {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                try {
                    int sleepSecond = ThreadLocalRandom.current().nextInt(5);
                    System.out.println(LocalDateTime.now() + ": Thread=" + Thread.currentThread().getId() + ", begin sleep, second=" + sleepSecond);
                    TimeUnit.SECONDS.sleep(sleepSecond);
                    System.out.println(LocalDateTime.now() + ": Thread=" + Thread.currentThread().getId() + ", begin end, second=" + sleepSecond);
                    countDownLatch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
        System.out.println(LocalDateTime.now() + ": await begin");
        countDownLatch.await();
        System.out.println(LocalDateTime.now() + ": await end");
    }

}

输出:

2020-01-16T19:15:56.263: await begin
2020-01-16T19:15:56.263: Thread=12, begin sleep, second=2
2020-01-16T19:15:56.263: Thread=11, begin sleep, second=1
2020-01-16T19:15:56.263: Thread=13, begin sleep, second=4
2020-01-16T19:15:57.265: Thread=11, begin end, second=1
2020-01-16T19:15:58.280: Thread=12, begin end, second=2
2020-01-16T19:16:00.277: Thread=13, begin end, second=4
2020-01-16T19:16:00.277: await end
阅读 394 · 发布于 2020-01-16

————        END        ————

扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看换一批