ReentrantLock 委派給內部類 Sync(繼承 AbstractQueuedSynchronizer)Sync 兩個子類:NonfairSync(預設)、FairSyncLockSupport、Unsafe 進行線程阻塞/喚醒與 CAS 操作final boolean nonfairTryAcquire(int acquires) {
Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
// 無鎖時 CAS 佔用
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
} else if (current == getExclusiveOwnerThread()) {
// 重入:直接疊加 state
int nextc = c + acquires;
if (nextc < 0) throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
特點:非公平搶佔、重入無需 CAS、偏向當前持有線程。
addWaiter 快速尾插(CAS),失敗進 enq 自旋入隊final boolean acquireQueued(final Node node, int arg) {
boolean interrupted = false;
for (;;) {
Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node); // 成功掛為頭節點
p.next = null; // help GC
return interrupted;
}
// 前驅非頭或獲取失敗 → 判斷是否應阻塞
if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt())
interrupted = true;
}
}
SIGNAL → 可安全 parkCANCELLED → 跳過取消節點重鏈SIGNAL,下輪嘗試LockSupport.park(this); // 交給 OS 核心阻塞
return Thread.interrupted();
protected final boolean tryRelease(int releases) {
int c = getState() - releases;
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
LockSupport.unpark(thread) 喚醒非公平特性:新來線程可能在 nonfairTryAcquire 直接搶佔,排隊線程不一定優先獲得。
protected final boolean tryAcquire(int acquires) {
Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
// 公平:檢查隊列是否有前驅等待者
if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
} else if (current == getExclusiveOwnerThread()) {
// 重入邏輯相同
}
return false;
}
state 表示鎖計數Condition 同樣基於 AQS 實現