synchronized 保證同一時間只有一個線程執行被修飾的方法或代碼塊,實現線程安全。
synchronized(this) 塊,同一時刻僅一線程執行。synchronized(this) 塊均阻塞。synchronized method 相當於 synchronized(this){...} 包裹全方法體。inner 對象則阻塞該對象的所有同步區域。public class Thread1 implements Runnable {
public void run() {
synchronized(this) {
for (int i=0; i<5; i++)
System.out.println(Thread.currentThread().getName() + " loop " + i);
}
}
public static void main(String[] args) {
Thread1 t1 = new Thread1();
new Thread(t1, "A").start();
new Thread(t1, "B").start();
}
}
// 輸出:A 0-4 後 B 0-4,串行
public void m4t1() { synchronized(this){ ... } }
public void m4t2() { ... } // 無 synchronized
// t1 執行 m4t1,t2 執行 m4t2 → 交替輸出,並發
public synchronized void m4t1() { ... }
public synchronized void m4t2() { ... }
// 即使調用不同方法,同一對象下也串行
public static synchronized void staticSync() { ... }
// 不同實例調用仍串行,鎖是 Class 對象
synchronized(inner) { inner.m4t1(); } // 鎖 inner
inner.m4t2(); // 非同步,可並發
// 若 m4t2 加 synchronized,則也被阻塞
| 維度 | 同步方法 | 同步塊 |
|---|---|---|
| 粒度 | 粗粒度(整方法) | 細粒度(指定代碼段) |
| 鎖對象 | 隱式 this / Class | 顯式指定任意對象 |
| 靈活性 | 低 | 高 |
| 性能 | 較差(鎖範圍大) | 較好(縮小臨界區) |
run())上加 synchronized。private final Object lock = new Object();理解 synchronized 的鎖機制、對象鎖與類鎖區別、同步塊優勢,是編寫高併發安全代碼的基礎。