一、AbstractQueuedSynchronizer是什么?
- 队列同步器
- Lock锁实现依赖
- Condition精准唤醒实现依赖
- BlockingQueue阻塞队列实现依赖
- ThreadPoolExecutor线程池实现依赖阻塞队列
- 线程辅助类:CountDownLatch,CyclicBarrier,Semaphore的实现依赖
发现这些东西都是面试中:并发,juc方面常见的面试题。 他们都直接或间接依赖AQS。
AQS很重要!!!AQS很重要!!!AQS很重要!!!
二 、类结构
AQS
public abstract class AbstractQueuedSynchronizer
extends AbstractOwnableSynchronizer
implements java.io.Serializable {
//队列元素
static final class Node {...}
//头节点
private transient volatile Node head;
//尾节点
private transient volatile Node tail;
//同步状态
private volatile int state;
//偏移量,AQS实现依赖Unsafe的CAS.
private static final long stateOffset;
private static final long headOffset;
private static final long tailOffset;
private static final long waitStatusOffset;
private static final long nextOffset;
//同步队列入队
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) {
//队列不存在,创建一个傀儡节点
if (compareAndSetHead(new Node()))
tail = head;
} else {
//形成队列
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
}
Node
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;
static final int PROPAGATE = -3;
//当前节点等待状态
volatile int waitStatus;
//构建双向同步队列
//前节点
volatile Node prev;
//后节点
volatile Node next;
//线程
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() {
}
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;
}
}