ホームページ  >  記事  >  Java  >  Java では、Thread の wait() メソッドと wait(long) メソッドをいつ呼び出すことができますか?

Java では、Thread の wait() メソッドと wait(long) メソッドをいつ呼び出すことができますか?

WBOY
WBOY転載
2023-09-03 23:41:09945ブラウズ

Java では、Thread の wait() メソッドと wait(long) メソッドをいつ呼び出すことができますか?

オブジェクトに対して wait() メソッドが呼び出されるたびに、現在のスレッドは別のスレッドが notify() を呼び出すまで待機します。または、このオブジェクトの notifyAll() メソッドを使用します。一方、wait(long timeout) を使用すると、現在のスレッドは、別のスレッドが notify() または を呼び出すまで待機します。 NoticeAll( ) このオブジェクトのメソッド、または指定されたタイムアウト期間が経過しました。

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 {
<strong>            this.wait(1000); 
</strong>            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 では、Thread の wait() メソッドと wait(long) メソッドをいつ呼び出すことができますか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。