CountDownLatch 源码分析
await 逻辑
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
Sync 的方法
// 获取共享锁,只有state==0 才成功获取锁,否则都需要等待
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
countDown逻辑
public void countDown() {
sync.releaseShared(1);
}
Sync 类的方法
protected boolean tryReleaseShared(int releases) {
for (;;) {
int c = getState();
if (c == 0)
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc))
// 只有状态等于0,才能唤醒等待队列中节点
return nextc == 0;
}
}
总结
CountDownLatch的实现也比较简单,利用AQS的共享锁来实现的,如果state==0,才能 await成功,否则需要等待。