// ❌ 錯誤:直接調用 run(),單線程順序執行
thread.run();
// ✅ 正確:start() 創建新線程,異步執行 run()
thread.start();
start() 請求 JVM 創建新線程,進入就緒狀態;run() 只是普通方法調用,不具備多線程特性。
public class ThreadLocalDemo {
// 靜態 ThreadLocal,每線程獨立副本
private static final ThreadLocal threadCounter =
ThreadLocal.withInitial(() -> 0);
public static void increment() {
threadCounter.set(threadCounter.get() + 1);
}
public static int get() {
return threadCounter.get();
}
public static void remove() {
threadCounter.remove(); // 防內存洩漏,線程池必須調用
}
}
remove(),否則 Key 弱引用失效,Value 強引用無法 GC// ❌ 拋出 IllegalMonitorStateException:無同步鎖
public void badWait() {
this.wait(); // 必須在 synchronized(this) 或 synchronized 方法中
}
// ✅ 正確:持有對象鎖
public synchronized void goodWait() throws InterruptedException {
this.wait(1000); // 釋放鎖,進入等待集
}
public synchronized void notifyOthers() {
this.notifyAll(); // 喚醒等待集線程,進入鎖池競爭
}
核心規則:調用 wait/notify 必須持有該對象的監視器鎖,否則拋出 IllegalMonitorStateException(RuntimeException,無需捕獲)。
| 方法 | 所屬類 | 釋放鎖 | 用途 | 備註 |
|---|---|---|---|---|
| sleep(ms) | Thread | ❌ 保持鎖 | 定時暫停 | 靜態方法,作用於當前線程 |
| wait() | Object | ✅ 釋放鎖 | 線程通信 | 需在同步塊中,進入等待集 |
| yield() | Thread | ❌ 保持鎖 | 禮讓 CPU | 就緒狀態,不保證調度 |
| suspend() | Thread | ❌ 保持鎖 | 掛起線程 | 已棄用,極易死鎖 |
public class SyncDemo {
// 類鎖:Class 對象,鎖住整個類
public synchronized static void staticMethod() { }
// 對象鎖:this,僅鎖住當前實例
public synchronized void instanceMethod() { }
}
SyncDemo.class,全類範圍互斥this,實例範圍互斥public class SyncTest {
public synchronized void method1() { sleep(1000); }
public synchronized void method2() { sleep(1000); }
public static void main(String[] args) {
SyncTest obj = new SyncTest();
new Thread(() -> obj.method1()).start(); // Thread-1
new Thread(() -> obj.method2()).start(); // Thread-2
// 輸出順序:method1 完成後 method2 才開始(串行)
}
}
同一對象的多個同步實例方法互斥,因共享 this 鎖。不同對象則不互斥。
java.util.concurrent 高級組件(ReentrantLock、CountDownLatch、Semaphore、ConcurrentHashMap)Executors 或自定義 ThreadPoolExecutor,拒絕策略、監控指標CompletableFuture、虛擬線程 (JDK 21+)