Node内部类
static final class Node {
// 共享模式标示
static final Node SHARED = new Node();
//独占模式标示
static final Node EXCLUSIVE = null;
/**
* waitStatus 值:
* 1:代表线程取消;
* -1:代表需要
* -2:代表线程等待
* -3:
*/
static final int CANCELLED = 1;
static final int SIGNAL = -1;
static final int CONDITION = -2;
static final int PROPAGATE = -3;
volatile int waitStatus;
volatile Node prev;
volatile Node next;
//线程使用后,设置为null
volatile Thread thread;
Node nextWaiter;
//判断当前节点是否为共享模式
final boolean isShared() {
return nextWaiter == SHARED;
}
//获取当前节点的前驱节点
final Node predecessor() throws NullPointerException {
Node p = prev;
if (p == null)
throw new NullPointerException();
else
return p;
}
Node() {
}
Node(Thread thread, Node mode) { // Used by addWaiter
this.nextWaiter = mode;
this.thread = thread;
}
Node(Thread thread, int waitStatus) { // Used by Condition
this.waitStatus = waitStatus;
this.thread = thread;
}
}
一系列CAS操作,线程安全
/**
* CAS操作
*/
private static final Unsafe unsafe = Unsafe.getUnsafe();
//state偏移量
private static final long stateOffset;
//head偏移量
private static final long headOffset;
//tail偏移量
private static final long tailOffset;
//node waitStatus偏移量
private static final long waitStatusOffset;
//node next偏移量
private static final long nextOffset;
static {
try {
stateOffset = unsafe.objectFieldOffset
(AbstractQueuedSynchronizer.class.getDeclaredField("state"));
headOffset = unsafe.objectFieldOffset
(AbstractQueuedSynchronizer.class.getDeclaredField("head"));
tailOffset = unsafe.objectFieldOffset
(AbstractQueuedSynchronizer.class.getDeclaredField("tail"));
waitStatusOffset = unsafe.objectFieldOffset
(Node.class.getDeclaredField("waitStatus"));
nextOffset = unsafe.objectFieldOffset
(Node.class.getDeclaredField("next"));
} catch (Exception ex) { throw new Error(ex); }
}
/**
* CAS head field. Used only by enq.
* CAS修改头部,用于enq()方法
*/
private final boolean compareAndSetHead(Node update) {
return unsafe.compareAndSwapObject(this, headOffset, null, update);
}
/**
* CAS tail field. Used only by enq.
* CAS修改尾部,用于enq()方法
*/
private final boolean compareAndSetTail(Node expect, Node update) {
return unsafe.compareAndSwapObject(this, tailOffset, expect, update);
}
/**
* CAS waitStatus field of a node.
* CAS 修改节点的waitStatus值
*/
private static final boolean compareAndSetWaitStatus(Node node,
int expect,
int update) {
return unsafe.compareAndSwapInt(node, waitStatusOffset,
expect, update);
}
/**
* CAS next field of a node.
* CAS修改节点的next节点
*/
private static final boolean compareAndSetNext(Node node,
Node expect,
Node update) {
return unsafe.compareAndSwapObject(node, nextOffset, expect, update);
}