Java Concurrent: CountDownLatch
Java juc 大约 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
阅读 629 · 发布于 2020-01-16
————        END        ————
扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Spring Boot无法写出Cookie阅读 590
-
Java Concurrent: CyclicBarrier阅读 441
-
JavaScript获取本地局域网IP地址阅读 1161
-
Linux升级OpenSSL版本阅读 1417
-
Linux之CentOS yum更换镜像阅读 614
-
设计模式之解释器模式阅读 495
-
MongoDB提示None of the hosts for replica set could be contacted阅读 406
-
Android MediaMetadataRetriever获取多媒体文件信息阅读 1749
-
OpenResty整合LuaRocks - Windows10阅读 917
-
PostgreSQL备份与还原阅读 1396