Java 中 wait()、notify() 和 notifyAll() 方法的重要性?
執行緒可以透過 Java 中的 wait()、notify() 和 notifyAll() 方法相互通訊。它們是 Object 類中定義的 final 方法,只能在同步上下文中呼叫。wait() 方法表示當前執行緒等待,直到另一個執行緒為此物件呼叫 notify() 或 notifyAll() 方法。
notify() 方法喚醒在該物件監視器上等待的單個執行緒。notifyAll() 方法喚醒在該物件監視器上等待的所有執行緒。執行緒透過呼叫其中一種 wait() 方法來等待物件監視器。如果當前執行緒不是物件監視器的所有者,則這些方法會引發 IllegalMonitorStateException。
wait() 方法語法
public final void wait() throws InterruptedException
notify() 方法語法
public final void notify()
notifyAll() 方法語法
public final void notifyAll()
示例
public class WaitNotifyTest {
private static final long SLEEP_INTERVAL = 3000;
private boolean running = true;
private Thread thread;
public void start() {
print("Inside start() method");
thread = new Thread(new Runnable() {
@Override
public void run() {
print("Inside run() method");
try {
Thread.sleep(SLEEP_INTERVAL);
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
synchronized(WaitNotifyTest.this) {
running = false;
WaitNotifyTest.this.notify();
}
}
});
thread.start();
}
public void join() throws InterruptedException {
print("Inside join() method");
synchronized(this) {
while(running) {
print("Waiting for the peer thread to finish.");
wait(); //waiting, not running
}
print("Peer thread finished.");
}
}
private void print(String s) {
System.out.println(s);
}
public static void main(String[] args) throws InterruptedException {
WaitNotifyTest test = new WaitNotifyTest();
test.start();
test.join();
}
}
輸出
Inside start() method Inside join() method Waiting for the peer thread to finish. Inside run() method Peer thread finished.
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
javascript
PHP