CountDownLatch解析

CountDownLatch是什么

CountDownLatch是基于AQS的阻塞工具,阻塞一个或者多个线程,直到所有的线程都执行完成。

CountDownLatch解决了什么问题

当一个任务运算量比较大的时候,需要拆分为各种子任务,必须要所有子任务完成后才能汇总为总任务。
使用并发模拟的时候可以使用CountDownLatch.也可以设置超时等待时间,

CountDownLatch 用法

1.阻塞所有线程执行完成后再执行

  1. @Slf4j
  2. public class CountDownLatchExample {
  3. //线程数量
  4. private static final int THREAD_NUM = 10;
  5. // CountdownLatch阻塞模拟
  6. public static void main(String[] args) throws InterruptedException {
  7. // 创建线程池 用于执行线程
  8. ExecutorService executorService = Executors.newCachedThreadPool();
  9. //创建countDownLatch
  10. final CountDownLatch countDownLatch = new CountDownLatch(THREAD_NUM);
  11. long startTime = System.currentTimeMillis();
  12. //循环创建线程
  13. for (int i = 0; i < THREAD_NUM; i++) {
  14. final int a = i;
  15. executorService.execute(() -> {
  16. try {
  17. test(a);
  18. } catch (Exception e) {
  19. log.error("Exception", e);
  20. } finally {
  21. countDownLatch.countDown();
  22. }
  23. });
  24. }
  25. countDownLatch.await();
  26. long endTime = System.currentTimeMillis();
  27. log.info("执行完毕,{}-{}",startTime,endTime);
  28. executorService.shutdown();
  29. }
  30. private static void test(int num) throws InterruptedException {
  31. Thread.sleep(100);
  32. log.info("{}-{}", num,System.currentTimeMillis());
  33. Thread.sleep(100);
  34. }
  35. }

结果
10:56:02.544 [pool-1-thread-5] INFO AQSExample.CountDownLatchExampleTimeOutTest - 4-1559271362542
10:56:02.543 [pool-1-thread-2] INFO AQSExample.CountDownLatchExampleTimeOutTest - 1-1559271362541
10:56:02.548 [pool-1-thread-10] INFO AQSExample.CountDownLatchExampleTimeOutTest - 9-1559271362548
10:56:02.544 [pool-1-thread-7] INFO AQSExample.CountDownLatchExampleTimeOutTest - 6-1559271362543
10:56:02.543 [pool-1-thread-4] INFO AQSExample.CountDownLatchExampleTimeOutTest - 3-1559271362542
10:56:02.544 [pool-1-thread-3] INFO AQSExample.CountDownLatchExampleTimeOutTest - 2-1559271362541
10:56:02.544 [pool-1-thread-8] INFO AQSExample.CountDownLatchExampleTimeOutTest - 7-1559271362543
10:56:02.544 [pool-1-thread-6] INFO AQSExample.CountDownLatchExampleTimeOutTest - 5-1559271362543
10:56:02.543 [pool-1-thread-1] INFO AQSExample.CountDownLatchExampleTimeOutTest - 0-1559271362541
10:56:02.548 [pool-1-thread-9] INFO AQSExample.CountDownLatchExampleTimeOutTest - 8-1559271362548
10:56:02.548 [main] INFO AQSExample.CountDownLatchExampleTimeOutTest - 执行完毕,1559271362441-1559271362548
上述结果可以看到,所有的线程执行完毕后主线程才打印出“执行完毕”。
CountDownLatch解析 - 图1

2.按照超时时间阻塞所有线程执行,到时间后直接释放。

如果我们设置超时时间之后

  1. @Slf4j
  2. public class CountDownLatchExampleTimeOutTest {
  3. //线程数量
  4. private static final int THREAD_NUM = 10;
  5. // CountdownLatch阻塞模拟
  6. public static void main(String[] args) throws InterruptedException {
  7. // 创建线程池 用于执行线程
  8. ExecutorService executorService = Executors.newCachedThreadPool();
  9. //创建countDownLatch
  10. final CountDownLatch countDownLatch = new CountDownLatch(THREAD_NUM);
  11. //循环创建线程
  12. long startTime = System.currentTimeMillis();
  13. for (int i = 0; i < THREAD_NUM; i++) {
  14. final int a = i;
  15. executorService.execute(() -> {
  16. try {
  17. test(a);
  18. } catch (Exception e) {
  19. log.error("Exception", e);
  20. } finally {
  21. countDownLatch.countDown();
  22. }
  23. });
  24. }
  25. countDownLatch.await(10,TimeUnit.MILLISECONDS);
  26. long endTime = System.currentTimeMillis();
  27. log.info("执行完毕,{}-{}",startTime,endTime);
  28. executorService.shutdown();
  29. }
  30. private static void test(int num) throws InterruptedException {
  31. Thread.sleep(50);
  32. log.info("{}-{}", num,System.currentTimeMillis());
  33. }
  34. }

由于每个线程延迟50毫秒之后再执行,count已经超时了所以优先打印出了执行完毕的结果。然后在继续执行线程中的内容。
结果
11:14:55.509 [main] INFO AQSExample.CountDownLatchExampleTimeOutTest - 执行完毕,1559272495373-1559272495506
11:14:55.542 [pool-1-thread-1] INFO AQSExample.CountDownLatchExampleTimeOutTest - 0-1559272495542
11:14:55.542 [pool-1-thread-2] INFO AQSExample.CountDownLatchExampleTimeOutTest - 1-1559272495542
11:14:55.543 [pool-1-thread-3] INFO AQSExample.CountDownLatchExampleTimeOutTest - 2-1559272495543
11:14:55.543 [pool-1-thread-4] INFO AQSExample.CountDownLatchExampleTimeOutTest - 3-1559272495543
11:14:55.543 [pool-1-thread-5] INFO AQSExample.CountDownLatchExampleTimeOutTest - 4-1559272495543
11:14:55.544 [pool-1-thread-6] INFO AQSExample.CountDownLatchExampleTimeOutTest - 5-1559272495544
11:14:55.544 [pool-1-thread-7] INFO AQSExample.CountDownLatchExampleTimeOutTest - 6-1559272495544
11:14:55.545 [pool-1-thread-9] INFO AQSExample.CountDownLatchExampleTimeOutTest - 8-1559272495545
11:14:55.545 [pool-1-thread-8] INFO AQSExample.CountDownLatchExampleTimeOutTest - 7-1559272495545
11:14:55.545 [pool-1-thread-10] INFO AQSExample.CountDownLatchExampleTimeOutTest - 9-1559272495545

CountDownLatch源码解析

CountDownLatch源码中的方法和属性并不多,下面我们来一一解析。

1.AQS框架以及构造方法

  1. //当前对象中私有阻塞工具
  2. private final Sync sync;
  3. // 模板方法模式重写AQS工具
  4. private static final class Sync extends AbstractQueuedSynchronizer {
  5. private static final long serialVersionUID = 4982264981922014374L;
  6. // 共享阻塞AQS
  7. Sync(int count) {
  8. setState(count);
  9. }
  10. // 获取当前还剩多少资源可以使用
  11. int getCount() {
  12. return getState();
  13. }
  14. protected int tryAcquireShared(int acquires) {
  15. return (getState() == 0) ? 1 : -1;
  16. }
  17. protected boolean tryReleaseShared(int releases) {
  18. for (;;) {
  19. int c = getState();
  20. if (c == 0)
  21. return false;
  22. int nextc = c-1;
  23. if (compareAndSetState(c, nextc))
  24. return nextc == 0;
  25. }
  26. }
  27. }
  28. //构造方法创建一个锁对象
  29. public CountDownLatch(int count) {
  30. if (count < 0) throw new IllegalArgumentException("count < 0");
  31. this.sync = new Sync(count);
  32. }

2.countDown()方法解析

该方法用于线程执行完毕后减计统计数量,

  1. // 该方法时释放一个共享锁。当所有锁都被释放完成后主线程就能继续执行了。
  2. public void countDown() {
  3. sync.releaseShared(1);
  4. }

3.await()方法解析

  1. //拦截主线程的方法。主线程在这里等待条件达成后继续执行。
  2. public void await() throws InterruptedException {
  3. //在这里阻塞线程的执行
  4. sync.acquireSharedInterruptibly(1);
  5. }
  6. public final void acquireSharedInterruptibly(int arg)
  7. throws InterruptedException {
  8. if (Thread.interrupted())
  9. throw new InterruptedException();
  10. //这里判断是否还有可以共享的资源
  11. // 如果有则返回-1 否则返回 1,重写AQS的方法参见(1.AQS框架以及构造方法)
  12. if (tryAcquireShared(arg) < 0)
  13. // 有资源则运行阻塞自旋等待所有线程执行完毕
  14. doAcquireSharedInterruptibly(arg);
  15. // 无资源可用就让线程继续执行
  16. }
  17. // 带延迟的减少数据拦截方法
  18. // 返回的结果是没有跑完全部线程就继续执行下一步了。
  19. public boolean await(long timeout, TimeUnit unit)
  20. throws InterruptedException {
  21. return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
  22. }
  23. public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout)
  24. throws InterruptedException {
  25. //线程如果被中断则抛出异常
  26. if (Thread.interrupted())
  27. throw new InterruptedException();
  28. // 表示如果线程被执行完了直接返回成功,如果没有执行完则看等待时间来决定是否要继续执行。
  29. return tryAcquireShared(arg) >= 0 ||
  30. doAcquireSharedNanos(arg, nanosTimeout);
  31. }

CountDownLatch 总结

CountDownLatch这个类能够使一个线程等待其他线程完成各自的工作后再执行。 在分散计算统一合成结果,按某个流程加载资源的方面有着非诚好用的效果。下一篇我们讲解像蓄水池一样功能的Semphore。