首頁 > Java > java教程 > 主體

在Java中,wait()、notify()和notifyAll()方法的重要性是什麼?

WBOY
發布: 2023-09-04 09:57:06
轉載
1292 人瀏覽過

在Java中,wait()、notify()和notifyAll()方法的重要性是什麼?

執行緒之間可以透過 Java 中的 wait()、notify() notifyAll() 方法相互通訊。這些是在Object類別中定義的最終方法,只能從同步上下文中呼叫。 wait() 方法會導致目前執行緒等待,直到另一個執行緒呼叫該物件的 notify() notifyAll() 方法。 notify() 方法喚醒正在等待該物件監視器的單一執行緒notifyAll() 方法喚醒所有正在等待該物件監視器的執行緒。執行緒透過呼叫 wait() 方法之一來等待物件的監視器。如果目前執行緒不是物件監視器的擁有者,這些方法可能會拋出 IllegalMonitorStateException

wait() 方法語法

public final void wait() throws InterruptedException
登入後複製

notify()方法語法

public final void notify()
登入後複製

NotifyAll() 方法語法

public final void notifyAll()<strong>
</strong>
登入後複製

範例

public class WaitNotifyTest {
   private static final long SLEEP_INTERVAL<strong> </strong>= 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.
登入後複製

以上是在Java中,wait()、notify()和notifyAll()方法的重要性是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!