1.CountDownLatch的await方法
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
然后调用
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;
}
countdown的state数量(也是CountDownLatch的count数量)不为0 所以返回 -1,然后调用doAcquireSharedInterruptibly,将当前线程加入到阻塞的线程并将当前线程阻塞
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);
}
}
然后把当前线程加到阻塞的队列中,并把当前线程给 阻塞掉
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
2.CountDownLatch的countdown方法
public void countDown() {
sync.releaseShared(1);
}
调用
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
首先调用,tryReleaseShared采用cas 循环自旋的方式将当前的state 减去1,如果已经被别的线程减到到0了,返回false(防止多个线程都重复唤醒被阻塞的线程),首次减到0的时候返回true,否则也返回fasle
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;
}
}
tryReleaseShared 返回true的时候开始调用 doReleaseShared()方法,将队列中被阻塞的线程唤醒
private void doReleaseShared() {
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;
}
}