官方解釋
- wait(),notify()和notifyAll()都是java.lang.Object的方法:
- wait(): Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
- notify(): Wakes up a single thread that is waiting on this object's monitor.
- notifyAll(): Wakes up all threads that are waiting on this object's monitor.
作用
- 實現線程間阻塞(Blocking)
- 控制進程內調度(inter-process communication)
調用前提
- 必須先獲得鎖
- 必須鎖定該對象
不獲得鎖會怎樣
public static void main(String[] args) throws InterruptedException {
Object obj = new Object();
obj.wait();
obj.notifyAll();
}
- 拋出java.lang.IllegalMonitorStateException的異常
不獲得該對象的鎖會怎樣
public static void main(String[] args) throws InterruptedException {
Object obj = new Object();
Object lock = new Object();
synchronized (lock) {
obj.wait();
obj.notifyAll();
}
}
- 拋出java.lang.IllegalMonitorStateException的異常
為什麼必須獲得該對象的鎖
- 沒有鎖,wait 和 notify 有可能會產生競態條件(Race Condition)
- 所以,JVM 通過在執行的時候拋出IllegalMonitorStateException的異常,來確保wait, notify時,獲得了對象的鎖,從而消除隱藏的Race Condition。
閱讀更多 白色蝸牛 的文章