Provides a framework for implementing blocking locks and related synchronizers (semaphores, events, etc) that rely on first-in-first-out (FIFO) wait queues.
如java API AbstractQueuedSynchronizer文档所言--其是为方便实现依赖于先进先出等待队列的阻塞锁和相关的同步器(semaphores -信号量,events )提供的一种框架。
FIFO队列:每个节点代表一个线程
static final class Node {
static final Node SHARED = new Node(); //说明节点的类型--共享的还是独占的
static final Node EXCLUSIVE = null;
static final int CANCELLED = 1; //等待状态--表示需要把这个线程从阻塞队列中移除
static final int SIGNAL = -1; //表示这个线程可以获得锁
static final int CONDITION = -2; //表示这个线程在执行条件等待--condition.await()
static final int PROPAGATE = -3; //共享锁的等待状态
volatile int waitStatus; //volatile 线程的状态更行对其它线程可见
volatile Node prev; //前节点
volatile Node next; //后节点
/**
* The thread that enqueued this node. Initialized on
* construction and nulled out after use.
*/
volatile Thread thread;
Node nextWaiter;
/**
* Returns true if node is waiting in shared mode
*/
final boolean isShared() {
return nextWaiter == SHARED;
}
final Node predecessor() throws NullPointerException {
Node p = prev;
if (p == null)
throw new NullPointerException();
else
return p;
}
Node() { // Used to establish initial head or SHARED marker
}
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;
}
}
让我们从ReentrantLock调用序列开始了解:
ReentrantLock
|------lock()
|----------acquire()
|-------------tryAcquire() //尝试申请锁 若失败则加入等待队列
|-------------acquireQueued()
|-------------------addWaiter() //将申请锁失败而阻塞的线程加入到队列末尾