| 寫法 | 鎖對象 | 等價展開 |
|---|---|---|
synchronized(this) { ... } | 當前實例 this | 同步塊,僅鎖住大括號內代碼 |
public synchronized void method() { ... } | 當前實例 this | 整個方法體等同於 synchronized(this) { methodBody } |
public static synchronized void method() { ... } | 類對象 MyClass.class | 等同於 synchronized(MyClass.class) { ... } |
synchronized(MyClass.class) { ... } | 類對象 MyClass.class | 鎖住所有實例共享的靜態資源 |
private final Object lock = new Object();),避免暴露 this 被外部惡意鎖死。public class Account {
private final Object balanceLock = new Object(); // 不暴露 this
private long balance = 0;
public void deposit(long amount) {
synchronized (balanceLock) { // 僅鎖存款邏輯
balance += amount;
}
// 其他非關鍵操作(日誌、通知)在鎖外執行
log.info("Deposited: {}", amount);
}
}
FileLock、Mutex (API 26+) 或資料庫事務,synchronized 僅限進程內。synchronized(this) 與 synchronized method 鎖對象相同(實例),差異在**鎖範圍**。實務中**優先使用私有 final Object 鎖**,精確控制臨界區,避免死鎖與並發度退化。