线程池使用countdownlatch
时间: 2023-10-13 18:06:09 浏览: 49
线程池使用CountDownLatch可以实现等待所有线程执行完毕后再执行某些操作的效果。具体实现方式是在每个线程执行完毕后,调用CountDownLatch的countDown()方法,表示一个线程已经执行完毕,然后在主线程中调用await()方法,等待所有线程执行完毕后再继续执行。
示例代码如下:
```java
public class ThreadPoolDemo {
public static void main(String[] args) throws InterruptedException {
int threadCount = 10;
CountDownLatch countDownLatch = new CountDownLatch(threadCount);
ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
for (int i = 0; i < threadCount; i++) {
executorService.execute(() -> {
// 执行任务
// ...
countDownLatch.countDown();
});
}
countDownLatch.await();
// 所有线程执行完毕后执行的操作
// ...
executorService.shutdown();
}
}
```