synchronized 僅能鎖定方法/代碼塊,無法跨方法、跨對象實現複雜同步。Doug Lea 的 concurrent 包(現納入 JDK 5+ java.util.concurrent)提供工業級同步組件。
public interface Sync {
void acquire() throws InterruptedException; // 獲取許可(阻塞)
boolean attempt(long msecs) throws InterruptedException; // 嘗試獲取(帶超時)
void release(); // 釋放許可
}
優勢:可跨方法、跨對象傳遞鎖對象,靈活替代 synchronized。
Sync gate = ...;
public void m() {
try {
gate.acquire();
try {
// 臨界區代碼
} finally {
gate.release(); // 異常也能釋放
}
} catch (InterruptedException ex) {
// 中斷處理
}
}
非重入互斥鎖,核心字段 boolean inuse_。
public void acquire() throws InterruptedException {
if (Thread.interrupted()) throw new InterruptedException();
synchronized (this) {
try {
while (inuse_) wait(); // 自旋等待
inuse_ = true;
} catch (InterruptedException ex) {
notify(); // 喚醒其他等待者
throw ex;
}
}
}
public synchronized void release() {
inuse_ = false;
notify(); // 喚醒一個等待者
}
帶超時嘗試獲取,利用 wait(long) 計時,超時返回 false。
每個節點持有獨立 Mutex,遍歷時「手手相傳」獲取下一節點鎖再釋放當前鎖,實現高並發鏈表操作。