jdk 基于 8 版本
在平时的开发中,我们经常会用到 CountDownLatch, 它是用于线程通信的工具类。
常用使用场景就是,主线程等待子线程操作完成,然后继续执行。
使用方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| public class CountDownLatchTest {
@Test
@SneakyThrows
void test() {
CountDownLatch countDownLatch = new CountDownLatch(1);
System.out.println(Thread.currentThread() + ": 1");
new Thread(() -> {
System.out.println(Thread.currentThread() + ": 2");
countDownLatch.countDown();
}).start();
System.out.println(Thread.currentThread() + ": 3");
countDownLatch.await();
System.out.println(Thread.currentThread() + ": 4");
}
}
|
执行结果: