Java Object notifyAll() メソッド
Object notifyAll() メソッドは、そのオブジェクト上で待機しているすべてのスレッドを起動します。
notifyAll() メソッドはnotify() メソッドと同じですが、違いは notifyAll() メソッドがこのオブジェクトのモニター上で待機しているすべてのスレッドを起動するのに対し、notify() メソッドは1つのスレッドだけを起動することです。
現在のスレッドがオブジェクトモニターの所有者でない場合、notifyAll() メソッドを呼び出すと同様にIllegalMonitorStateException例外が発生します。
構文
public final void notifyAll()
パラメータ
无 。
戻り値
戻り値はありません。
例
次の例は、notifyAll() メソッドの使用を示しています。
例
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class サンプルTest {
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 Object クラス