wait():釋放鎖、進入等待集合、阻塞直到 notify()/notifyAll()/中斷/超時notify():喚醒任一等待該物件鎖的線程notifyAll():喚醒所有等待該物件鎖的線程class ThreadB extends Thread {
int total = 0;
@Override
public void run() {
synchronized (this) { // 鎖定 this (ThreadB 實例)
System.out.println("ThreadB running...");
for (int i = 0; i < 100; i++) {
total += i;
}
notify(); // 喚醒等待 this 鎖的線程 (ThreadA)
}
}
}
public class ThreadA {
public static void main(String[] args) {
ThreadB b = new ThreadB();
b.start();
System.out.println("b started...");
synchronized (b) { // 同一把鎖:ThreadB 實例
try {
System.out.println("Waiting for b to complete...");
b.wait(); // 釋放 b 的鎖,進入等待
// 被喚醒後,重新獲得鎖,繼續執行
System.out.println("Completed. Back to main thread");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Total is: " + b.total); // 4950
}
}
時間軸:
ThreadA: start() → synchronized(b) → wait() [釋放鎖, 進入 WAITING]
↑
ThreadB: run() → synchronized(this) → 計算 → notify() [喚醒]
↓
ThreadA: [從 WAITING 移至 BLOCKED 等待鎖] → 獲得鎖 → 繼續執行
| 錯誤代碼 | 問題 | 修正 |
|---|---|---|
synchronized(b) { b.wait(); } 但 b.run() 未 synchronized | IllegalMonitorStateException | 雙方必須同步於同一物件 |
| 在非 synchronized 方法中呼叫 wait() | 同左 | 移入 synchronized 區塊 |
使用 Thread.currentThread() 作為鎖 | 主線程與子線程鎖不同,無法喚醒 | 使用共享物件 (如共享資料物件、this、專用 lock 物件) |
| wait() 無迴圈檢查條件 | 虛假喚醒 | while(!condition) wait(); |
class SharedBuffer {
private final List<Integer> buffer = new ArrayList<>();
private final int capacity;
public SharedBuffer(int capacity) { this.capacity = capacity; }
public synchronized void produce(int value) throws InterruptedException {
while (buffer.size() == capacity) wait(); // 滿則等待
buffer.add(value);
notifyAll(); // 喚醒消費者
}
public synchronized int consume() throws InterruptedException {
while (buffer.isEmpty()) wait(); // 空則等待
int value = buffer.remove(0);
notifyAll(); // 喚醒生產者
return value;
}
}
java.util.concurrent:BlockingQueue (ArrayBlockingQueue)、CountDownLatch、CyclicBarrier、Semaphore、PhaserLock/Condition:ReentrantLock + newCondition(),支援多條件變數、公平鎖、可中斷鎖CompletableFuture / Parallel Streams:函數式非阻塞協作建議:新代碼優先使用 java.util.concurrent 高階組件;維護舊代碼或教學時才直接操作 wait/notify。理解其底層機制有助於排查死鎖、活鎖、飢餓等並發問題。