Java Object wait() メソッド

Java String类Java Object クラス


Object wait() メソッドは、現在のスレッドを待機状態にします。他のスレッドがこのオブジェクトのnotify() メソッド或 notifyAll() メソッド。

現在のスレッドはこのオブジェクトのモニターの所有者である必要があります。そうでない場合は、まだIllegalMonitorStateException例外が発生します。

現在のスレッドが待機前または待機中に任意のスレッドによって中断された場合、InterruptedException例外がスローされます。

構文

public final void wait()

パラメータ

  • 无 。

戻り値

戻り値はありません。

例

以下の例は、wait() メソッドの使用法を示しています:

例

import java.util.Collections; import java.util.LinkedList; import java.util.List; public class サンプルTest extends Object { private List synchedList; public サンプルTest() { //同期リストを作成します synchedList = Collections.synchronizedList(new LinkedList()); } //リスト内の要素を削除します public String removeElement() throws InterruptedException { synchronized (synchedList) { //リストが空の場合は待機します while (synchedList.isEmpty()) { System.out.println("List is empty..."); synchedList.wait(); System.out.println("Waiting..."); } String element = (String) synchedList.remove(0); return element; } } //リストに要素を追加します public void addElement(String element) { System.out.println("Opening..."); synchronized (synchedList) { //要素を追加し、要素が存在することを通知します synchedList.add(element); System.out.println("New Element:'" + element + "'"); synchedList.notifyAll(); System.out.println("notifyAll called!"); } System.out.println("Closing..."); } public static void main(String[] args) { final サンプルTest demo = new サンプルTest(); Runnable runA = new Runnable() { public void run() { try { String item = demo.removeElement(); System.out.println("" + item); } catch (InterruptedException ix) { System.out.println("Interrupted Exception!"); } catch (Exception x) { System.out.println("Exception thrown."); } } }; Runnable runB = new Runnable() { //要素追加操作を実行し、ループを開始します public void run() { demo.addElement("Hello!"); } }; try { Thread threadA1 = new Thread(runA, "Google"); threadA1.start(); Thread.sleep(500); Thread threadA2 = new Thread(runA, "サンプル"); threadA2.start(); Thread.sleep(500); Thread threadB = new Thread(runB, "Taobao"); threadB.start(); Thread.sleep(1000); threadA1.interrupt(); threadA2.interrupt(); } catch (InterruptedException x) { } } }

上記のプログラムの実行結果は次のとおりです:

List is empty...
List is empty...
Opening...
New Element:'Hello!'
notifyAll called!
Closing...
Waiting...
Waiting...
List is empty...
Hello!
Interrupted Exception!

Java String类Java Object クラス

その他の拡張