我有以下程序:
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 看起来很简单的领域,并且由于示例不多,在概念上给我留下了很大的差距。
最佳答案
你在 obj
上调用了 wait
和 notifyAll
,但是你在 this
上同步(因为你有同步方法)。
为了等待或通知,你需要先“拥有”监视器。取消同步方法,改为在 obj 上同步:
public void flag() {
System.out.println("Before Wait");
synchronized (obj) {
try {
obj.wait();
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
}
System.out.println("After Being Notified");
}
public void unflag() {
System.out.println("Before Notify All");
synchronized (obj) {
obj.notifyAll();
}
System.out.println("After Notify All Method Call");
}
关于java - 了解 Java Wait 和 Notify 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2624503/