大家好 我是积极向上的湘锅锅💪💪💪
1. 什么是AQS?
AQS,英文名是AbstractQueuedSychronizer,翻译过来就是抽象队列同步器
可以看我们的java.util.concurrent.locks下面,会发现AQS其实就是一个抽象类
AQS 为构建锁和同步器提供了一些通用功能的是实现,因此,使用 AQS 能简单且高效地构造出应用广泛的大量的同步器,比如我们提到的 ReentrantLock,Semaphore等等
2. AQS 原理
AQS 核心思想是,如果被请求的共享资源空闲,则将当前请求资源的线程设置为有效的工作线程,并且将共享资源设置为锁定状态。如果被请求的共享资源被占用,那么就需要一套线程阻塞等待以及被唤醒时锁分配的机制,这个机制 AQS 是用 CLH 队列锁实现的,即将暂时获取不到锁的线程加入到队列中------>出自JavaGuide
可以看到,AQS 使用一个 volatile int state 成员变量来表示同步状态,通过内置的 FIFO 队列(多线程争用资源被阻塞时会进入此队列)来完成获取资源线程的排队工作。AQS 使用 CAS 对该同步状态进行原子操作实现对其值的修改
private volatile int state;/*共享变量,使用volatile保证可见性*/
其中state 的访问方式有三种:
- getState() 获取当前同步器的值
- setState() 设置当前同步器的值
- compareAndSetState() 调用unsafe类进行原地CAS
/**
* Returns the current value of synchronization state.
* This operation has memory semantics of a {@code volatile} read.
* @return current state value
*/
protected final int getState() {
return state;
}
/**
* Sets the value of synchronization state.
* This operation has memory semantics of a {@code volatile} write.
* @param newState the new state value
*/
protected final void setState(int newState) {
state = newState;
}
/**
* Atomically sets synchronization state to the given updated
* value if the current state value equals the expected value.
* This operation has memory semantics of a {@code volatile} read
* and write.
*
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful. False return indicates that the actual
* value was not equal to the expected value.
*/
protected final boolean compareAndSetState(int expect, int update) {
// See below for intrinsics setup to support this
return unsafe.compareAndSwapInt(t