在 AQS 源码解读之加锁中,线程 A 占用着锁没有释放。然后线程 B 和线程 C 都在 CHL 队列中排队,也就是执行了 parkAndCheckInterrupt 方法将自己挂起了。现在 CHL 队列的状态:
线程 A
unlock() 方法解析
ReentrantLock 类中的 unlock 方法
public void unlock() {
sync.release(1);
}
sync 类中的 release 方法
public final boolean release(int arg) {
// 主要是修改 state 的值和设置占用锁的线程
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
AbstractQueuedSynchronizer 类中的抽象 tryRelease 方法
protected boolean tryRelease(int arg) {
throw new UnsupportedOperationException();
}
sync 类中的具体实现
// releases = 1
protected final boolean tryRelease(int releases) {
// 获取 state 的值,之前被线程 A 设置成 1 现在一减等于 0
int c = getState() - releases;// c = 0
// 判断当前线程是否等于占用锁的线程
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
// c = 0 条件成立
if (c