public final void signal() { if (!isHeldExclusively()) throw new IllegalMonitorStateException(); Node first = firstWaiter; if (first != null) doSignal(first); }
doSignal
private void doSignal(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) {
//-2 表示需要Signal 的节点
if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
//一般不会发生
return false;
// 从条件队列转移到阻塞队列
Node p = enq(node); // p为node的前一个节点
int ws = p.waitStatus; //如果为p的状态为-1,则它有责任直接唤醒当前node
if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
LockSupport.unpark(node.thread);
return true;
}
enq 转移到阻塞队列
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) { // Must initialize
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}