Java Object notify() メソッド
Object notify() メソッドは、このオブジェクトのモニター上で待機しているスレッドを1つ起こすために使用されます。
すべてのスレッドがこのオブジェクト上で待機している場合、1つのスレッドだけが選択され、選択は任意であり、実装が決定を行う際に発生します。
スレッドがオブジェクトモニター上で待機するには、wait() メソッドを呼び出すことができます。
notify() メソッドは、このオブジェクトのモニターの所有者であるスレッドのみが呼び出すことができます。
スレッドがオブジェクトモニターの所有者になるには、次の3つの方法を使用できます:
- オブジェクトの同期インスタンスメソッドを実行する
- synchronized 組み込みロックを使用する
- Class 型のオブジェクトに対して、同期静的メソッドを実行する
一度に1つのスレッドだけがオブジェクトのモニターを所有できます。
現在のスレッドがこのオブジェクトのモニターの所有者でない場合は、IllegalMonitorStateException例外がスローされます。
構文
public final void notify()
パラメータ
无 。
戻り値
戻り値はありません。
例
以下の例は、notify() メソッドの使用法を示しています:
例
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 クラス