AQS(一种实现锁机制的框架,也可以说一些基类组合构建锁和同步器)
一:基本概念
AQS框架:全称AbstractQueuedSynchronizer。(抽象队列同步)
AQS是一个用来构建锁和同步器的(各种基类)框架,使用AQS能简单且高效地构造出应用广泛的大量的同步器,比如我们提到的ReentrantLock,Semaphore,其他的诸如ReentrantReadWriteLock,SynchronousQueue,FutureTask等等皆是基于AQS的。当然,我们自己也能利用AQS非常轻松容易地构造出符合我们自己需求的同步器。
总结:手撕核心类AbstractQueuedSynchronizer,你会对AQS认识更加深刻,然后Count
二:AQS基本原理的详细分析
类图分析(下面会详细说明)
基本锁的特性:
加锁、解锁
以ReentrantLock为例:
可重入锁,公平锁,非公平锁
可重入锁,公平锁,非公平锁概念自行知乎
上述概念结合源码进行分析(以ReentrantLock为例)
private final Sync sync;
// ReentrantLock的加锁方法
public void lock() {
sync.lock();
}
//ReentrantLock 释放锁
public void unlock() {
sync.release(1);
}
// 以下代码是ReentrantLock实现公平锁和非公平锁的构造方法
/**
* Creates an instance of {@code ReentrantLock}.
* This is equivalent to using {@code ReentrantLock(false)}.
* 默认非公平锁
*/
public ReentrantLock() {
sync = new NonfairSync();
}
/**
* Creates an instance of {@code ReentrantLock} with the
* given fairness policy.
* 公平锁
* @param fair {@code true} if this lock should use a fair ordering policy
*/
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
实现公平,非公平的详细过程后续会详细讲到
AbstractQueuedSynchronizer核心类
/**
* Acquires in exclusive mode, ignoring interrupts. Implemented
* by invoking at least once {@link #tryAcquire},
* returning on success. Otherwise the thread is queued, possibly
* repeatedly blocking and unblocking, invoking {@link
* #tryAcquire} until success. This method can be used
* to implement method {@link Lock#lock}.
*
* @param arg the acquire argument. This value is conveyed to
* {@link #tryAcquire} but is otherwise uninterpreted and
* can represent anything you like.
*/
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
// 唤醒queue中的线程;addWaiter向队列中添加线程