在 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()

更新日期:2023 年 11 月 22 日

528 次觀看

開啟您的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.