Java Object wait(long timeout) メソッド
Object wait(long timeout) メソッドは、現在のスレッドを待機(ブロック)状態にし、他のスレッドがこのオブジェクトのnotify() メソッド或 notifyAll() メソッドが呼び出されるか、またはパラメータ timeout に設定されたタイムアウト時間を超えるまで待機します。
timeout パラメータが 0 の場合、タイムアウトせず、待機し続けます。これは次のメソッドと似ています:wait() メソッド。
現在のスレッドはこのオブジェクトのモニターのオーナーである必要があります。そうでない場合は、やはりIllegalMonitorStateException例外が発生します。
現在のスレッドが待機前または待機中に任意のスレッドによって中断された場合、InterruptedException例外がスローされます。
渡されたパラメータが不正な場合、IllegalArgumentException例外がスローされます。
構文
public final void wait(long timeout)
パラメータ
timeout- 待機時間(ミリ秒単位)。
戻り値
戻り値はありません。
例
以下の例では、wait(long timeout) メソッドの使用方法を示しています:
例
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(10000); //待機時間を設定する
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 Object クラス