CountDownLatch
2、node设置 preNode的 ws为 -1 ;然后 唤醒队列中线程,清除队列节点。
后人把前人的 ws 改为 -1 ,就是为了到时候 前人能把 后人叫醒!
(自己付出努力,只为自己能醒过来!)
1、唤醒队列中线程,清除队列节点。
2、node设置 preNode的 ws为 -1
1、
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
2、
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
3、
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
4、
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);
}
}
5、
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)
/*
* This node has already set status asking a release
* to signal it, so it can safely park.
*/
return true;
if (ws > 0) {
/*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
/*
* waitStatus must be 0 or PROPAGATE. Indicate that we
* need a signal, but don't park yet. Caller will need to
* retry to make sure it cannot acquire before parking.
*/
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
6、
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}