tatic final class Node {
/** Marker to indicate a node is waiting in shared mode */staticfinal Node SHARED = new Node(); //共享模式/** Marker to indicate a node is waiting in exclusive mode */staticfinal Node EXCLUSIVE = null; //独占模式/** waitStatus value to indicate thread has cancelled */staticfinalint CANCELLED = 1; ////因为超时或者中断,node会被设置成取消状态,被取消的节点时不会参与到竞争中的,会一直保持取消状态不会转变为其他状态; /** waitStatus value to indicate successor's thread needs unparking */staticfinalint SIGNAL = -1; //若节点的后继节点被阻塞,当前节点释放锁或者取消的时候需要唤醒后继者。 /** waitStatus value to indicate thread is waiting on condition */staticfinalint CONDITION = -2; //表明线程在等待中/**
* waitStatus value to indicate the next acquireShared should
* unconditionally propagate
*/staticfinalint PROPAGATE = -3; //该状态表示下一次节点如果是Shared的,则无条件获取锁。volatileint waitStatus; //节点的状态值volatile Node prev; //前节点volatile Node next; //后节点 volatile Thread thread; //节点关联线程
Node nextWaiter; //连接到下一个节点等待条件,或特殊值共享
privatestatic boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus; //下一个节点的等待状态if (ws == Node.SIGNAL) //signal 状态则正常放回/*
* This node has already set status asking a release
* to signal it, so it can safely park.
*/returntrue;
if (ws > 0) {
/*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/do { //如要将所有>0 即取消的节点都排除
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.
*///cas 操作将节点的waitStatus标记为signal状态
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
returnfalse;
}
privatevoid unparkSuccessor(Node node) {
/*
* If status is negative (i.e., possibly needing signal) try
* to clear in anticipation of signalling. It is OK if this
* fails orif status is changed by waiting thread.
*/
int ws = node.waitStatus; //获取线程的下一个节点的等待状态if (ws < 0)
compareAndSetWaitStatus(node, ws, 0); //标记该节点线程已经被释放
/*
* Thread to unpark is held in successor, which is normally
* just the next node. But if cancelled or apparently null,
* traverse backwards from tail to find the actual
* non-cancelled successor.
*/
Node s = node.next;
//如果下一个节点为null,或者状态为取消if (s == null || s.waitStatus > 0) {
s = null;
//从尾部开始寻找一个可以被唤醒的节点,尾部节点是稳定的for (Node t = tail; t != null && t != node; t = t.prev)
if (t.waitStatus <= 0)
s = t;
}
if (s != null)
LockSupport.unpark(s.thread);
}