AQS 是實現(xiàn)大部分同步組件的基礎
被推薦為定義為自定義同步組件的非public靜態(tài)內(nèi)部類
- 通過AQS提供的如下方法對需要用戶重寫的方法(要修改同步器狀態(tài))提供了支持
- 需要重寫的方法
- 對外暴露的模板方法
- 模板設計模式
模板設計模式的意圖是定義算法的整體骨架,然后將部分針對特定細節(jié)的部分聲明為抽象方法逼迫子類去實現(xiàn)(AQS是拋出異常,而不是定義為抽象方法)
- 例子
這是AQS源碼附帶的實例程序
public class Mutex implements Lock {
private static class Sync extends AbstractQueuedSynchronizer {
//是否處于占用狀態(tài)
protected boolean isHeldExclusive() {
return getState() == 1;
}
//當狀態(tài)為 0 時獲取鎖
@SuppressWarnings("Since15")
public boolean tryAcquired(int acquires) {
if (compareAndSetState(0, 1)) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
//釋放鎖,將狀態(tài)設置為 0
@SuppressWarnings("Since15")
protected boolean tryRelease(int releases) {
if (getState() == 0) {
throw new IllegalMonitorStateException();
}
setExclusiveOwnerThread(null);
setState(0);
return true;
}
//返回一個Condition,每個condition都包含了一個condition的對隊列
Condition newCondition(){
return new ConditionObject();
}
}
//僅僅將操作代理到 Sync 上即可
private final Sync sync = new Sync();
public void lock() {
sync.acquire(1);
}
public boolean tryLock() {
return sync.tryAcquired(1);
}
public void unlock() {
sync.release(1);
}
public Condition newCondition() {
return sync.newCondition();
}
public boolean isLocked(){
return sync.isHeldExclusive();
}
public boolean hasQueuedThread(){
return sync.hasQueuedThreads();
}
public void lockInterruptibly() throws InterruptedException{
sync.acquireInterruptibly(1);
}
public boolean tryLock(long timeOut, TimeUnit unit) throws InterruptedException{
return sync.tryAcquireNanos(1,unit.toNanos(timeOut));
}
}
在自定義同步組件中的public方法中,去調(diào)用靜態(tài)內(nèi)部類AQS的模板方法,來實現(xiàn)其自定義的同步功能。


