我有一个以下的程序:
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
。
但是如果我使用SimpleWaitNotify的监视器,程序执行将被暂停。换句话说,我认为它会暂停当前执行线程,从而暂停执行者。任何有助于理解正在发生的事情的帮助都将不胜感激。
这是一个理论和javadoc似乎很简单的领域,由于没有太多的例子,在概念上留下了一个很大的空白。