使用AQS(AbtractQueuedSynchronizer)来构建锁和synchronizer的框架,令人惊讶的是,使用AQS能简单且高效地构造出应用广泛的大量的synchronizer。一个基于AQS的synchronized所执行的基本操作,是一些不同形式的获取和释放。
操作规范式
boolean acquire() throws InteruptedException{
while (state does notpermit acquire){
if(blocking acquisition requested){
enqueuecurrent thread if not already queued
block current thread
}
else
returnfailure
}
possiblyupdate synchronization state
dequuethread if it was queued
returnsucess
}
void release(){
update synchronization state
if (new state may permit a blocked thread to acquire)
unblock on or more queued threads
}