0%

CountDownLatch

倒计数器, 在完成倒计数后, 等待在倒计数器上的线程才能继续执行.

特点:

  • CountDownLatch 在计数为 0 之后无法重置, 所以不可复用.
  • 工作线程完成任务之后, 不会阻塞等待其他线程完成.

1. API

  • CountDownLatch(count)
    指定计数
  • countDown
    在任务线程中倒数, 表示该任务已完成
  • await
    在主线程中等待所有任务完成

2. 使用场景

  1. 将异步代码变成同步代码

学习自 redisson 的源码: org.redisson.command.CommandAsyncService#await

1
2
3
4
5
6
7
8
@Override
public boolean await(RFuture<?> future, long timeout, TimeUnit timeoutUnit) throws InterruptedException {
CountDownLatch l = new CountDownLatch(1);
future.onComplete((res, e) -> {
l.countDown();
});
return l.await(timeout, timeoutUnit);
}