在 Java 中,我們什麼時候可以呼叫某個執行緒的 wait() 和 wait(long) 方法?
只要對某個物件呼叫 wait() 方法,就會使當前執行緒等待,直到另一個執行緒為該物件呼叫 notify() 或 notifyAll() 方法,而 wait(long timeout) 會使當前執行緒等待,直到另一個執行緒為該物件呼叫 notify() 或 notifyAll() 方法,或指定超時時間已過。
wait()
在以下程式中,當對某個物件呼叫 wait() 時,該執行緒將從執行狀態進入等待狀態。它等待其他執行緒呼叫 notify() 或 notifyAll() 才能進入可執行狀態,這將形成死鎖。
示例
class MyRunnable implements Runnable {
public void run() {
synchronized(this) {
System.out.println("In run() method");
try {
this.wait();
System.out.println("Thread in waiting state, waiting for some other threads on same object to call notify() or notifyAll()");
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
}
public class WaitMethodWithoutParameterTest {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable, "Thread-1");
thread.start();
}
}
輸出
In run() method
wait(long)
在以下程式中,當對某個物件呼叫 wait(1000) 時,該執行緒將從執行狀態進入等待狀態,即使在呼叫 notify() 或 notifyAll() 之後,在超時時間過後的執行緒,仍將從等待狀態進入可執行狀態。
示例
class MyRunnable implements Runnable {
public void run() {
synchronized(this) {
System.out.println("In run() method");
try {
this.wait(1000);
System.out.println("Thread in waiting state, waiting for some other threads on same object to call notify() or notifyAll()");
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
}
public class WaitMethodWithParameterTest {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable, "Thread-1");
thread.start();
}
}
輸出
In run() method Thread in waiting state, waiting for some other threads on same object to call notify() or notifyAll()
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP