public synchronized void method()synchronized(表達式) { ... } —— 更靈活,可指定鎖物件。
public class SyncBlock {
public void method1() {
synchronized(this) { ... } // 等同於方法加 synchronized
}
public void method2() {
synchronized(this) { ... }
}
public synchronized void method3() { ... } // 寫法二
}
method1/2/3 任一時刻只能有一個執行。synchronized(OuterClass.this)。
public class StaticSyncBlock {
public static void method1() {
synchronized(StaticSyncBlock.class) { ... } // 必須用 Class 物件
}
public static synchronized void method2() { ... } // 寫法二
}
this,鎖為 Class 物件(.class 或 instance.getClass())。Class 鎖實現跨類同步。無論正常結束或拋出異常,JVM 保證離開區塊時釋放監視器鎖,無需手動 unlock。
private static String lock = "";
synchronized(lock) { ... } // 危險!
lock = "new"; // 重新賦值導致鎖物件改變,同步失效
解決:宣告 private final static String LOCK = "";,防止誤改鎖物件參考。
| 場景 | 鎖表達式 | 備註 |
|---|---|---|
| 實例方法互斥 | this 或 Outer.this | 預設行為 |
| 靜態方法互斥 | MyClass.class | 不可用 this |
| 跨類別靜態方法互斥 | SharedClass.class | 共用同一 Class 物件 |
| 同步區塊內拋異常 | 自動釋放 | 無需 finally |
| 基本型別鎖 | ❌ 不可 | 需包裝類或專用物件 |
final,避免參考被竄改。ReentrantLock 或 StampedLock 替代。