1 介绍

  • countDownLatch:用于记录这些线程能执行的次数 并不是说一个线程只能执行一次。 完全可以在一个线程的run()方法里调两次甚至更多次latch.countDown() 让你的初始化值减为零。
  • 通过一个计数器来实现的,计数器的初始值是线程的数量。每当一个线程执行完毕后,计数器的值就-1,当计数器的值为0时,表示所有线程都执行完毕,然后在闭锁上等待的线程就可以恢复工作了。

    2 API说明

  • 构造器

    1. //参数count为计数值
    2. public CountDownLatch(int count) { };
  • 类中有三个方法是最重要的:

    1. //调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
    2. public void await() throws InterruptedException { };
    3. //和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行
    4. public boolean await(long timeout, TimeUnit unit) throws InterruptedException { };
    5. //将count值减1
    6. public void countDown() { };

    3 案例

    1. public class CountDownLatchTest {
    2. public static void main(String[] args) {
    3. final CountDownLatch latch = new CountDownLatch(2);
    4. System.out.println("主线程开始执行…… ……");
    5. //第一个子线程执行
    6. ExecutorService es1 = Executors.newSingleThreadExecutor();
    7. es1.execute(new Runnable() {
    8. @Override
    9. public void run() {
    10. try {
    11. Thread.sleep(3000);
    12. System.out.println("子线程:"+Thread.currentThread().getName()+"执行");
    13. } catch (InterruptedException e) {
    14. e.printStackTrace();
    15. }
    16. latch.countDown();
    17. }
    18. });
    19. es1.shutdown();
    20. //第二个子线程执行
    21. ExecutorService es2 = Executors.newSingleThreadExecutor();
    22. es2.execute(new Runnable() {
    23. @Override
    24. public void run() {
    25. try {
    26. Thread.sleep(3000);
    27. } catch (InterruptedException e) {
    28. e.printStackTrace();
    29. }
    30. System.out.println("子线程:"+Thread.currentThread().getName()+"执行");
    31. latch.countDown();
    32. }
    33. });
    34. es2.shutdown();
    35. System.out.println("等待两个线程执行完毕…… ……");
    36. try {
    37. latch.await();
    38. } catch (InterruptedException e) {
    39. e.printStackTrace();
    40. }
    41. System.out.println("两个子线程都执行完毕,继续执行主线程");
    42. }
    43. }

    4 结果

    1. 主线程开始执行…… ……
    2. 等待两个线程执行完毕…… ……
    3. 子线程:pool-1-thread-1执行
    4. 子线程:pool-2-thread-1执行
    5. 两个子线程都执行完毕,继续执行主线程
  • 原文链接:https://www.jianshu.com/p/e233bb37d2e6