wait()/notify() 定義在 Object 中,意味著每個對象天然擁有監視器鎖與條件隊列。本文從底層語義切入,詳細闡述必須在 synchronized 中調用、wait 釋放鎖、notify 隨機喚醒、虛假喚醒需循環檢查等核心規則,並給出生產者-消費者交替打印的完整 Demo。
Object,非 Thread;鎖屬於對象,操作鎖的方法自然屬於對象。synchronized(obj) 塊中。wait() 釋放鎖,讓其他線程能進入同步塊調用 notify()。notify() 隨機喚醒一個等待線程;notifyAll() 喚醒所有,但只能搶到鎖的一個繼續執行。notify() 所在同步塊結束前,被喚醒線程仍處於阻塞狀態。synchronized(obj) {
while (!condition) { // 循環檢查防虛假喚醒
obj.wait(); // 釋放鎖並進入條件隊列
}
// 條件滿足,執行業務邏輯
}
class Business {
private boolean isMainThread = true;
public synchronized void sub(int i) {
while (!isMainThread) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } }
for (int j = 1; j <= 10; j++) System.out.println("sub thread " + j + ", loop " + i);
isMainThread = false; notify();
}
public synchronized void main(int i) {
while (isMainThread) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } }
for (int j = 1; j <= 100; j++) System.out.println("main thread " + j + ", loop " + i);
isMainThread = true; notify();
}
}
while 改用 if → 虛假喚醒導致邏輯錯誤。IllegalMonitorStateException。Condition。掌握底層語義,靈活組合 synchronized + wait/notify 或升級至 Lock + Condition,即可構建高可靠的並發協作組件。