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
阅读 2180 · 发布于 2020-01-16
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Spring Boot Slf4j MDC 实现全链路日志追踪阅读 974
-
IDEA 中使用 Lombok 报找不到 get/set 错误的方法解决方法阅读 3853
-
Windows 查看文件占用的几种方法阅读 5973
-
Elasticsearch 全文搜索 query->match阅读 1448
-
macOS IDEA 显示 .DS_Store 文件阅读 392
-
Java 并发编程之 happens-before 7 条规则阅读 1229
-
GoJS 右键菜单隐藏和显示事件监听阅读 1929
-
记一次小程序排查 setData 函数耗时很长思路阅读 3641
-
Spring Boot 使用 Jib 打包成 Docker 镜像阅读 623
-
Android 音量调节阅读 4058