次のプログラムがあります。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SimpleWaitNotify implements Runnable {
final static Object obj = new Object();
static boolean value = true;
public synchronized void flag() {
System.out.println("Before Wait");
try {
obj.wait();
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
System.out.println("After Being Notified");
}
public synchronized void unflag() {
System.out.println("Before Notify All");
obj.notifyAll();
System.out.println("After Notify All Method Call");
}
public void run() {
if (value) {
flag();
} else {
unflag();
}
}
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(4);
SimpleWaitNotify sWait = new SimpleWaitNotify();
pool.execute(sWait);
SimpleWaitNotify.value = false;
SimpleWaitNotify sNotify = new SimpleWaitNotify();
pool.execute(sNotify);
pool.shutdown();
}
}
obj を待機するException in thread "pool-1-thread-1" java.lang.IllegalMonitorStateException: current thread not owner
と、2 つのスレッドのそれぞれについて次の例外が発生します。
しかし、SimpleWaitNotify のモニターを使用すると、プログラムの実行が中断されます。つまり、現在の実行スレッドを一時停止し、実行者を一時停止すると思います。何が起こっているのかを理解するための助けをいただければ幸いです。
これは、理論とjavadocが単純に見える領域1であり、例があまりないため、概念的に大きなギャップがありました。