Java 并发编程之 CountDownLatch
Java juc 大约 1865 字作用
允许一个或多个线程等待,直到其他线程的一组操作完成后,再完成自身线程中暂停后的后续操作。
倒计时:到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
阅读 1691 · 发布于 2020-01-16
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Vue props 自定义属性阅读 105
-
Arthas 使用 monitor 在指定时间段内统计方法的调用次数、平均返回时间等阅读 2667
-
微信小程序基于 wxParse 实现代码高亮阅读 3552
-
MySQL 数据库设置 root 密码阅读 1059
-
Linux 命令之 Vim 显示行号阅读 1711
-
IDEA 复制弹框错误提示信息快捷键阅读 569
-
VirtualBox 虚拟机与宿主机时间同步阅读 637
-
Spring Boot 获取 HttpServletRequest 的几种方式阅读 365
-
PHP 关闭 X-Powered-By 信息阅读 1266
-
软考-系统架构设计师:信息系统阅读 1367