public synchronized void method()synchronized(表達式) { ... } — 更靈活、可見性更強public void method1() {
synchronized(this) { ... } // 等價於方法加 synchronized
}
public void method2() {
synchronized(this) { ... }
}
public synchronized void method3() { ... }
效果:同一實例下,method1/2/3 同一時間僅一個可執行。
注意:所有代碼必須在塊內,否則無法全方法同步。
別名:SyncBlock.this 等價於 this。
class InnerClass {
public void method4() {
synchronized(SyncBlock.this) { ... } // 鎖外部類實例
}
}
內部類 this 鎖內部實例,OuterClass.this 鎖外部實例,實現跨類同步。
synchronized 塊正常結束或異常拋出均自動釋放鎖,無需手動管理。
靜態方法調用不需要實例,不能用 this,必須用 Class 對象:
public static void method1() {
synchronized(StaticSyncBlock.class) { ... } // 類字面量獲取 Class
}
public static synchronized void method2() { ... }
效果:method1/2 同一時間僅一個可執行 (類級別鎖)。
類名.class (最常用、編譯期常量)實例.getClass() (運行時獲取,同類所有實例返回同一 Class)// Test 類靜態方法與 StaticSyncBlock 類靜態方法同步
public static void method() {
synchronized(StaticSyncBlock.class) { ... } // 共享同一 Class 鎖
}
| 方法類型 | 可用鎖 | 說明 |
|---|---|---|
| 非靜態 | this / 外部類.this / 任意共享對象 | 實例級鎖 |
| 靜態 | 類名.class / 實例.getClass() | 類級鎖 |
| 非靜態中同步靜態 | 類名.class | 可行 |
| 靜態中同步非靜態 | this | 不可行 (無 this) |