private static final int THREAD_NUMS = 8;
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(THREAD_NUMS);
for (int i = 0; i < THREAD_NUMS; i++) {
Thread t = new Thread(() -> {
try {
latch.await();
} catch (InterruptedException x) {
x.printStackTrace();
}
// 业务处理
});
t.start();
if (i + 1 < THREAD_NUMS) {// 保证最后一次countDown()先不调用
latch.countDown();
}
}
// 之所以让主线程休眠5秒就是确保其他线程都调用完了await(),让所有线程都阻塞,在调用最后一次的countDown()
Thread.sleep(5_000);
latch.countDown();
}
CountDownLatch实现并发控制
最新推荐文章于 2023-08-19 18:46:55 发布