0
我想尝试使用Object本地方法wait()和notify()而不是Condition变量,但是这会引发IllegalMonitorStateException ...请解释如何使用它?你能解释为什么这段代码会引发异常吗?
package monitor;
public class MyMonitor {
private long threadID=0;
Object okToWrite = new Object();
Object okToRead = new Object();
synchronized public void insertID() throws InterruptedException {
if (this.threadID != 0) {
okToWrite.wait();
}
this.threadID = Thread.currentThread().getId();
okToRead.notify();
}
synchronized public long getID() throws InterruptedException {
long res;
if (this.threadID == 0) {
okToRead.wait();
}
System.out.println(this.threadID);
res = this.threadID;
this.threadID = 0;
okToWrite.notify();
return res;
}
}
是否需要进一步锁定Object?
UPDATE: 广告尼尔建议,有必要之前调用wait对象上同步或通知......我们开始吧:
package monitor;
public class MyMonitor {
private long threadID=0;
Object okToWrite = new Object();
Object okToRead = new Object();
public void insertID() throws InterruptedException {
if (this.threadID != 0) {
synchronized(okToWrite) {
okToWrite.wait();
}
}
this.threadID = Thread.currentThread().getId();
synchronized(okToRead) {
okToRead.notify();
}
}
public long getID() throws InterruptedException {
long res;
if (this.threadID == 0) {
synchronized(okToRead) {
okToRead.wait();
}
}
System.out.println(this.threadID);
res = this.threadID;
this.threadID = 0;
synchronized(okToWrite) {
okToWrite.notify();
}
return res;
}
}
非常感谢!我明白了,不是有效的!我要发布正确的代码...谢谢你的朋友 – user1576208 2013-02-23 19:44:41