我有以下程序:
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 看起来很简单的领域 1,由于没有太多示例,因此在概念上给我留下了很大的空白。