CountDownLatch的作用,就是将多个线程阻塞,等待某一事件触发后,再同时将阻塞的多个线程放行。
如果你对ReentrantLock,ReentrantReadWriteLock足够了解的话,通过CountDownLatch的功能,不难想到,CountDownLatch要阻塞多个线程并做到同时放行,所以他的await肯定是使用的共享锁进行阻塞。而创建CountDownLatch的时候,指定的count数量,肯定保存在AQS的state中,await的时候,如果state不为0,将将线程阻塞挂起。当调用countDown时候,就将state减1,当state为0的时候,就释放共享锁,共享锁的释放是一个链式反应,就会将阻塞的线程全部释放掉。
CountDownLatch是通过共享锁实现的,如果对ReentrantReadWriteLock不熟悉的,请先看ReentrantReadWriteLock源码分析。弄明白了共享锁,理解CountDownLatch就很简单了。
CountDownLatch创建
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
//设置state的值为count
Sync(int count) {
setState(count);
}
CountDownLatch.await
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
//只要state不等于,就会返回-1,将线程阻塞
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
//就是将线程挂起,如果一旦一个线程获取锁成功,在setHeadAndPropagate会紧接着唤醒后续的线程
//中断异常会通过throws往外抛
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) {
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.countDown
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
//释放共享锁,就是对state进行减法操作,如果state为0了,就返回true、返回true将会唤醒被挂起的线程
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;
}
}
//释放被挂起的第一个线程,当这个线程获取锁之后,在doAcquireSharedInterruptibly中的setHeadAndPropagate中会继续释放下一个线程。
private void doReleaseShared() {
/*
* Ensure that a release propagates, even if there are other
* in-progress acquires/releases. This proceeds in the usual
* way of trying to unparkSuccessor of head if it needs
* signal. But if it does not, status is set to PROPAGATE to
* ensure that upon release, propagation continues.
* Additionally, we must loop in case a new node is added
* while we are doing this. Also, unlike other uses of
* unparkSuccessor, we need to know if CAS to reset status
* fails, if so rechecking.
*/
for (;;) {
Node h = head;
if (h != null && h != tail) {
int ws = h.waitStatus;
if (ws == Node.SIGNAL) {
if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
continue; // loop to recheck cases
unparkSuccessor(h);
}
else if (ws == 0 &&
!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
continue; // loop on failed CAS
}
if (h == head) // loop if head changed
break;
}