CountDownLatch 强调的是一个线程(或多个)需要等待另外的 n 个线程干完某件事情之后才能继续执行。

测试案例

  1. package com.personal.test.countdownlatch;
  2. import java.util.Random;
  3. import java.util.concurrent.CountDownLatch;
  4. public class Test20201225162321 {
  5. public static void test20201225162329() {
  6. CountDownLatch latch = new CountDownLatch(2);
  7. Test20201225162416 t1 = new Test20201225162416(latch);
  8. Test20201225162416 t2 = new Test20201225162416(latch);
  9. new Thread(t1).start();
  10. new Thread(t2).start();
  11. }
  12. public static void main(String[] args) {
  13. Test20201225162321.test20201225162329();
  14. }
  15. }
  16. class Test20201225162416 implements Runnable {
  17. private final CountDownLatch latch;
  18. public Test20201225162416(CountDownLatch latch) {
  19. this.latch = latch;
  20. }
  21. @lombok.SneakyThrows
  22. @Override
  23. public void run() {
  24. System.out.println(Thread.currentThread().getName());
  25. Thread.sleep(new Random().nextInt(1) * 1000L);
  26. latch.countDown();
  27. }
  28. }

参考资料

https://www.cnblogs.com/csu_xajy/p/4338357.html
https://blog.csdn.net/yujin753/article/details/46125283