// 加 synchronized:串行輸出 0-4 兩次
// 無 synchronized:交替輸出 0,0,1,1... 並發執行
public synchronized void excute() { ... }
public synchronized void excute1() { ... }
// 即使調用不同方法,線程也串行,因為鎖的是同一對象
結論:對象鎖導致該對象所有同步方法互斥。
public static synchronized void excute() { ... }
public static synchronized void excute1() { ... }
// 不同實例調用仍串行,鎖是 Class 對象
結論:靜態同步方法鎖定 Class 對象,跨實例生效。
public void excute() {
synchronized(this) { ... } // 同步塊
}
public void excute1() {
synchronized(this) { ... }
}
// 效果等同於同步方法,但粒度可控
| 特性 | 同步方法 | 同步塊 |
|---|---|---|
| 鎖對象 | 隱式 this / Class | 顯式指定任意對象 |
| 鎖範圍 | 整個方法體 | 僅塊內代碼 |
| 靈活性 | 低 | 高(可縮小臨界區) |
| 性能 | 較差 | 較好 |
private final Object lock = new Object();同步方法是粗粒度並發控制,同步塊提供細粒度控制。合理選擇可顯著提升併發性能。