CountDownLatch允许一个或多个线程等待其他线程完成操作。
CountDownLatch的构造函数接收一个int类型的参数作为计数器,当我们调用countDown方法时,计数器会减1,await方法会阻塞当前线程,直到计数器变成0。
//countDown最后的执行逻辑
protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
for (;;) {
int c = getState();
if (c == 0)
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
//相应中断
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}