概述
AbstractQueuedSynchronizer,简称AQS,它提供了同步器框架的形象实现,ReentrantLock、Semaphore、CountDownLatch、CyclicBarrier等并发类均是基于AQS来实现的,具体用法是通过继承AQS实现其模板办法,而后将子类作为同步组件的外部类。
源码剖析
成员变量
head和tail节点
这俩个节点是Node类型的,前面会说先看代码
//期待队列的头节点,惰性初始化。除了初始化外只能被setHead办法批改,并且节点的waitStatus不能为CANCELLED
private transient volatile Node head;
//期待队列的尾节点,惰性初始化,只会在调用enq办法增加期待节点时批改
private transient volatile Node tail;
state
AQS维持了一个繁多的volatile的state变量,并通过unsafe办法来原子性的获取和设置该值
/**
* The synchronization state.
*/
private volatile int state;
protected final int getState() {
return state;
}
protected final void setState(int newState) {
state = newState;
}
protected final boolean compareAndSetState(int expect, int update) {
// See below for intrinsics setup to support this
return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}
spinForTimeoutThreshold
static final long spinForTimeoutThreshold = 1000L;
实现办法
private Node enq(final Node node) {
for (;;) {
Node t = tail;
//第一次入队,head和tail都为null
if (t == null) { // Must initialize
//原子设置头节点
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
//原子设置尾节点
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
应用传入的mode节点来让以后线程入队
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);
// Try the fast path of enq; backup to full enq on failure
Node pred = tail;
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node);
return node;
}
发表回复