synchronized 區塊語法:synchronized(鎖物件) { 同步程式碼 }。鎖物件決定了哪些執行緒會互斥。
public class SyncBlock {
public void method1() { synchronized(this) { ... } }
public void method2() { synchronized(this) { ... } }
public synchronized void method3() { ... } // 等價
}
synchronized(OuterClass.this)。
public class StaticSyncBlock {
public static void method1() { synchronized(StaticSyncBlock.class) { ... } }
public static synchronized void method2() { ... }
}
this,必須用 Class 物件(.class 或 instance.getClass())。Class 鎖實現跨類同步。JVM 保證離開區塊(正常或異常)自動釋放監視器,無需手動處理。
| 錯誤做法 | 後果 | 正確做法 |
|---|---|---|
靜態方法用 this | 編譯錯誤 | 用 MyClass.class |
| 同步區塊鎖字串並重新賦值 | 鎖物件改變,同步失效 | 宣告 final |
| 基本型別當鎖 | 編譯錯誤 | 用包裝類或專用 Object |
final、私有、不可變。ReentrantLock。