java - 使用多线程运行奇偶程序时出现异常

标签 java multithreading

我正在尝试运行下面编写的程序。但在这里我遇到了异常

Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at main.java.OddEven$even.run(OddEven.java:16)
at java.lang.Thread.run(Unknown Source)

我无法找到异常背后的原因。

notify 方法发生异常。仅当当前线程不拥有锁对象时,我们才会在notify方法中得到IllegalMonitorStateException。

public class OddEven {

private Integer count = 0;
Object ob = new Object();

class even implements Runnable {

    @Override
    public void run() {
            while (count % 2 == 0) {
                synchronized (ob) {
                if (count % 2 == 0) {
                    System.out.println(count++);
                    notify();
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }
        }

    }
}

class odd implements Runnable {
    @Override
    public void run() {
            while (count % 2 != 0) {
                synchronized (ob) {
                if (count % 2 != 0) {
                    System.out.println(count++);
                    notify();
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }
        }

    }

}

public static void main(String[] args) throws CloneNotSupportedException {
    OddEven t1 = new OddEven();
    Thread e = new Thread(t1.new even());
    Thread o = new Thread(t1.new odd());
    e.start();
    o.start();
}

}

最佳答案

要在对象上调用notify(),您需要对该对象有一个锁,即位于该对象上同步的 block 中。您位于同步块(synchronized block)中,但在 ob 上同步,同时在 this 上调用 notify()

您还必须对 notify()wait() 调用使用 ob,或者在 this< 上进行同步.

关于java - 使用多线程运行奇偶程序时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39866502/

相关文章:

java - 不幸的是,Android 应用程序已停止并可在 Android 设备上运行

java - Java 和 C/C++ 应用程序可以共享信号量吗?

multithreading - Spring Boot Web 应用程序中多个 REST 调用超时

Java 日历和日期格式

java - (Java) 无法捕获异常

java - 在 Apache Geronimo 中安装 Oracle jdbc 驱动程序

java - 线程连接自身

java - 从另一个 JFrame 调用 JFrame 方法

c++ - Visual C++ 如何用线程启动非 void 函数

c# - 使用在主线程中创建的 COM 对象无阻塞地运行一段代码