Mutex 實現 Sync,提供非重入、可中斷、帶超時的互斥語義。適用於「前置/後置」跨方法同步場景。
if (Thread.interrupted()) throw new InterruptedException();
雙重保障:運行態線程檢查中斷標誌;阻塞態(wait/sleep/join)拋出異常並清除標誌,捕獲後重新拋出保持中斷語義。
synchronized (this) {
while (inuse_) wait(); // 條件變量模式,防虛假喚醒
inuse_ = true;
}
long waitTime = msecs;
long start = System.currentTimeMillis();
for (;;) {
wait(waitTime);
if (!inuse_) { inuse_ = true; return true; }
waitTime = msecs - (System.currentTimeMillis() - start);
if (waitTime <= 0) return false;
}
注意:Object.wait(long) 非精確計時,僅適合粗略超時控制。
class Node {
Object item; Node next;
Mutex lock = new Mutex();
}
class List {
Node head;
synchronized Node getHead() { return head; }
boolean search(Object x) throws InterruptedException {
Node p = getHead();
if (p == null) return false;
p.lock.acquire(); // 首節點上鎖
try {
for (;;) {
if (x.equals(p.item)) return true;
Node next = p.next;
if (next == null) return false;
next.lock.acquire(); // 獲取下一節點鎖
p.lock.release(); // 釋放當前節點鎖
p = next;
}
} finally { /* 確保釋放 */ }
}
}
此模式將鎖粒度縮小到節點級,大幅提升並發吞吐。