1 CountDownLatch

n个异步全部结束后,另一个线程执行。

  1. CountDownLatch countDownLatch = new CountDownLatch(10);
  2. ThreadPoolExecutor pool = new ThreadPoolExecutor(10, 20, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(30));
  3. Runnable task = () -> {
  4. try {
  5. Thread thread = Thread.currentThread();
  6. System.out.println(thread.getName() + " 执行开始");
  7. sleep(1000);
  8. System.out.println(thread.getName() + " 执行结束");
  9. countDownLatch.countDown();
  10. } catch (InterruptedException e) {
  11. e.printStackTrace();
  12. }
  13. };
  14. for (int i = 0; i < 10; i++) {
  15. pool.execute(task);
  16. }
  17. try {
  18. // 当计数器减到0时 被阻塞线程继续执行。
  19. countDownLatch.await();
  20. } catch (InterruptedException e) {
  21. e.printStackTrace();
  22. }
  23. System.out.println("主线程结束了");

image.png
应用场景: 几个互不相干的操作,可以同时开多个线程同时开始,等这个几个操作到结束了,被阻塞的线程继续执行。