CountDownLatch的实现原理
CountDownLatch是一个同步计数器,能够保证在其他线程完成某一个业务操作前,当前线程一直处于等待/阻塞状态。具体来说,这个计数器将会从给定的某一个数值count开始,通过countDown()方法的调用进行倒数。当执行某一次countDown()操作后,计数器的count数值等于0,所有调用了await()方法的线程,就解除等待/阻塞状态继续执行。
实现原理:
在CountDownLatch中维持了一个队列同步器(AQS),这是一个锁,初始化时
public CountDownLatch(int count) {//count为锁中的state大小
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
其中count为state的大小
1、countDown方法
CountDownLatch的每次countDown方法都是对state -1
public void countDown() {
sync.releaseShared(1);
}
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; //state-1
if (compareAndSetState(c, nextc))//CAS原子操作
return nextc == 0;
}
}
2、await()函数
await函数是当前线程循环获取锁 ( 判断state是否为0 ),如果state为0,表示该线程前的其他线程已经执行完毕,当前线程获取到锁,可以继续执行
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) { //state为0时才能去获取锁
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
//CountDownLatch中自定义的队列同步器的方法
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}