final boolean isOnSyncQueue(Node node) {
if (node.waitStatus == Node.CONDITION || node.prev == null)
returnfalse;
if (node.next != null) // If has successor, it must be on queue
returntrue;
/*
* node.prev can be non-null, but not yet on queue because
* the CAS to place it on queue can fail. So we have to
* traverse from tail to make sure it actually made it. It
* will always be near the tail in calls to this method, and
* unless the CAS failed (which is unlikely), it will be
* there, so we hardly ever traverse much.
*/
return findNodeFromTail(node); //从尾部遍历,如果不在队列中则返回false
}
唤醒
signal
publicfinalvoidsignal() {
if (!isHeldExclusively()) //如果当前线程不是持有锁的线程,则抛异常thrownew IllegalMonitorStateException();
Node first = firstWaiter;
if (first != null)
doSignal(first); //将队列标记为signal 并入syc队列
}
doSignal
privatevoiddoSignal(Node first) {
do {
if ( (firstWaiter = first.nextWaiter) == null) //判断条件队列节点
lastWaiter = null;
first.nextWaiter = null;
} while (!transferForSignal(first) && //将条件队列入同步同列
(first = firstWaiter) != null);
}
transferForSignal
final boolean transferForSignal(Node node) {
/*
* If cannot change waitStatus, the node has been cancelled.
*/
if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
returnfalse;
/*
* Splice onto queue andtryto set waitStatus of predecessor to
* indicate that thread is (probably) waiting. If cancelled or
* attempt to set waitStatus fails, wake up to resync (in which
* case the waitStatus can be transiently and harmlessly wrong).
*/
Node p = enq(node); //入同步队列
int ws = p.waitStatus;
if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
LockSupport.unpark(node.thread);
returntrue;
}
doSignalAll
privatevoiddoSignalAll(Node first) {
lastWaiter = firstWaiter = null;
do {
Node next = first.nextWaiter;
first.nextWaiter = null;
transferForSignal(first); //一个个唤醒
first = next;
} while (first != null);
}
等待await public final void await() throws InterruptedException { if (Thread.interrupted()) //响应中断 throw new InterruptedException(); Node node = addConditionWaite