萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> XML 程式設計

Java 多線程核心機制:wait()/notify() 協同模式完整解析與經典範例

wait/notify 基礎契約

  • 必須在 synchronized 區塊/方法中呼叫 (持有物件監視器鎖)
  • wait():釋放鎖、進入等待集合、阻塞直到 notify()/notifyAll()/中斷/超時
  • notify():喚醒任一等待該物件鎖的線程
  • notifyAll():喚醒所有等待該物件鎖的線程
  • 喚醒後需重新獲取鎖才能繼續執行

經典範例:ThreadA 等待 ThreadB 完成累加

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() 未 synchronizedIllegalMonitorStateException雙方必須同步於同一物件
在非 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 5+)

  • java.util.concurrent:BlockingQueue (ArrayBlockingQueue)、CountDownLatch、CyclicBarrier、Semaphore、Phaser
  • Lock/Condition:ReentrantLock + newCondition(),支援多條件變數、公平鎖、可中斷鎖
  • CompletableFuture / Parallel Streams:函數式非阻塞協作

建議:新代碼優先使用 java.util.concurrent 高階組件;維護舊代碼或教學時才直接操作 wait/notify。理解其底層機制有助於排查死鎖、活鎖、飢餓等並發問題。

copyright © 萬盛學電腦網 all rights reserved