1 CountDownLatch
n个异步全部结束后,另一个线程执行。
CountDownLatch countDownLatch = new CountDownLatch(10);
ThreadPoolExecutor pool = new ThreadPoolExecutor(10, 20, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(30));
Runnable task = () -> {
try {
Thread thread = Thread.currentThread();
System.out.println(thread.getName() + " 执行开始");
sleep(1000);
System.out.println(thread.getName() + " 执行结束");
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
};
for (int i = 0; i < 10; i++) {
pool.execute(task);
}
try {
// 当计数器减到0时 被阻塞线程继续执行。
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程结束了");
应用场景: 几个互不相干的操作,可以同时开多个线程同时开始,等这个几个操作到结束了,被阻塞的线程继续执行。