2
我正在嘗試運行下面的書面程序。但在這裏我得到例外使用多線程運行Odd偶程序時得到異常
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)
我無法找到異常的原因。
Execption出現在通知方法中。只有當前線程不擁有鎖定對象時,我們纔會在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()'或'wait()',你可以在'this'上隱式調用它' – Gikkman
我在這裏沒有得到預期的輸出。應該是1 2 3 4 ..我只是得到1 2.你能幫我弄清楚錯誤嗎?我有正確的代碼,並沒有拋出異常。 –
你確定你也在'ob'上調用了'wait()'嗎? – Gikkman