我正在尝试运行下面编写的程序。但在这里我遇到了异常
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/