一、AQS是什么
AQS同步器是Java并发编程的基础,从资源共享的角度分成独占和共享两种模式,像ReentrantLock、ThreadPoolExecutor、CountDownLatch等都是基于AQS来实现的,如图:
二、AQS同步队列的基本结构
AQS维护了一个头节点(head)和一个尾节点(tail)结构的双向链表,当一个线程获取锁失败时,会将该线程打包成一个Node节点,挂到同步队列尾节点
1 private transient volatile Node head;//同步队列头结点
2 private transient volatile Node tail;//同步队列尾结点
3 private volatile int state;//同步状态
Node节点类(双向链表挂在同步器中)
1 static final class Node {
2
3 static final Node SHARED = new Node();//共享模式
4
5 static final Node EXCLUSIVE = null;//独占模式
6
7 static final int CANCELLED = 1;//线程已取消
8
9 static final int SIGNAL = -1;//后继线程需要取消挂起
10
11 static final int CONDITION = -2;//线程正在等待条件
12
13 static final int PROPAGATE = -3;
14
15 volatile int waitStatus;
16
17 volatile Node prev;//前驱结点
18
19 volatile Node next;//后继结点
20
21 volatile Thread thread;//当前线程
22
23 Node nextWaiter;
24
25 final boolean isShared() {
26 return nextWaiter == SHARED;
27 }
28
29 final Node predecessor() throws NullPointerException {
30 Node p = prev;
31 if (p == null)
32 throw new NullPointerException();
33 else
34 return p;
35 }
36
37 Node() {
38 }
39
40 Node(Thread thread, Node mode) {
41 this.nextWaiter = mode;
42 this.thread = thread;
43 }
44
45 Node(Thread thread, int waitStatus) {
46 this.waitStatus = waitStatus;
47 this.thread = thread;
48 }
49 }
三、AQS中最重要的成员变量state(同步状态)
所有对同步状态的改变,都是围绕着state来操作的
1 //volatile修饰state,确保内存可见性
2 //当前线程写的时候,其他线程可以直接读到这个值
3 private volatile int state;
4
5 //获取同步状态
6 protected final int getState() {
7 return state;
8 }
9
10 //设置同步状态
11 protected final void setState(int newState) {
12 state = newState;
13 }
14
15 //CAS原子操作设置同步状态
16 protected final boolean compareAndSetState(int expect, int update) {
17 // See below for intrinsics setup to support this
18 return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
19 }
四、需重写的抽象方法
AQS使用了模板方法设计模式,核心框架JDK已经写好,自定义同步器需只重写如下抽象方法,即可实现不同的同步器:
1 //用于判断当前方法是否被线程独占,独占锁需重写 2 protected boolean isHeldExclusively() { 3 throw new UnsupportedOperationException(); 4 } 5 6 //独占式获取锁 7 protected boolean tryAcquire(int arg) { 8 throw new UnsupportedOperationException(); 9 } 10 11 //独占式释放锁 12 protected boolean tryRelease(int arg) { 13 throw new UnsupportedOperationException(); 14 } 15 16 //共享式获取锁 17 protected int tryAcquireShared(int arg) { 18 throw new UnsupportedOperationException(); 19 } 20 21 //共享式释放锁 22 protected int tryReleaseShared(int arg) { 23 throw new UnsupportedOperationException(); 24 }
五、重要方法详解
待续...