AQS使用了一个int成员变量来表示同步状态,通过内置的FIFO队列来完成资源的获取
一、同步状态
/**
* The synchronization state.
*/
private volatile int state;
(1.6后新加入了变种的同步队列器主要区别在与同步状态long表示)
维护了以下三种方式访问state
getState()
setState(int newState)
compareAndSetState(int expect, int update)
二、同步队列
static final class Node {
/** Marker to indicate a node is waiting in shared mode */
static final Node SHARED = new Node();
/** Marker to indicate a node is waiting in exclusive mode */
static final Node EXCLUSIVE = null;
/** waitStatus value to indicate thread has cancelled */
static final int CANCELLED = 1;
/** waitStatus value to indicate successor's thread needs unparking */
static final int SIGNAL = -1;
/** waitStatus value to indicate thread is waiting on condition */
static final int CONDITION = -2;
...
}
一个双向的FIFO队列
当前线程获取同步状态失败时,会将当前线程以及其它等待信息封装成一个Node节点,将其加入同步队列,同时阻塞当前线程,-