CountDownLatch 介绍
类似发令枪,CountDownLatch的构造函数可以传入一个数字,代表倒计时多少个数。
主要方法:
- countDown:每调用一次countDown(),倒计时就会减少1,
- await:当倒计时到0时,await()方法就会停止阻塞
示例代码
public static void main(String[] args) throws InterruptedException {
int N = 10;
CountDownLatch latch = new CountDownLatch(N);
CountDownLatch lock = new CountDownLatch(1);
for (int i = 0; i < N; i++) {
Thread.sleep(100L);
new Thread(() -> {
try {
lock.await();
System.out.println("---> start " + Thread.currentThread().getName());
Thread.sleep(1000L);
System.out.println("---> end " + Thread.currentThread().getName());
latch.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
lock.countDown();
latch.await();
}