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

昵称:
随便看看换一批
- 走进Rust:枚举阅读 319
- IntelliJ中使用Lombok报找不到get/set错误的方法解决方法阅读 1039
- Nginx日志按天生成阅读 2518
- Android AlertDialog点击区域外不可取消,点击返回键可以与Activity同时撤销阅读 1622
- 算法每日一题20190623:最长公共前缀阅读 1121
- Linux安装运行keepalived阅读 768
- Spring Boot使用MongoTemplate操作MongoDB阅读 2955
- Linux之CentOS gcc版本升级为4.8.2方法阅读 498
- Gradle分析依赖关系阅读 1075
- MySQL之Windows免安装版本配置环境阅读 469