java - 了解 Java Wait 和 Notify 方法

标签 java multithreading wait

我有以下程序:

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 上调用了 waitnotifyAll,但是你在 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/

相关文章:

java - 有没有更好的方法来使用等待/通知与 AtomicInteger 连接

java - 准备语句因 DB2 SQL 错误而失败

java - java中如何将int值转换为char值

java - 从服务中检索位置

c# - ThreadPool.QueueUserWorkItem 的意外行为

c++ - 在互斥量上使用多个 std::unique_lock,FIFO 中的所有线程都等待进程?

multithreading - 使用 3 个条件变量同步 3 个线程

batch-file - 在 "IF EXIST"内,等待两个小时然后退出

java - JavaDoc 中是否应该描述 unchecked Exception?

java - 为什么 wait() 和 notify() 不在特殊类中?