Java 你能解释一下为什么这个代码会引发异常吗?

Java 你能解释一下为什么这个代码会引发异常吗?,java,Java,我想尝试使用对象本机方法wait()和notify()而不是条件变量,但这会引发IllegalMonitorStateException…您能解释一下如何使用它吗 package monitor; public class MyMonitor { private long threadID=0; Object okToWrite = new Object(); Object okToRead = new Object(); synchronized public void insert

我想尝试使用对象本机方法wait()和notify()而不是条件变量,但这会引发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;

}


}
对象是否需要进一步的锁

更新: Ad Neil建议,在调用wait或notify之前,有必要在对象上进行同步…现在开始:

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;

}


}

您可以通过同步要等待或通知的对象使代码正常工作,但我只需同步监视器对象上的所有内容:

package monitor;

public class MyMonitor {
    private long threadID = 0;

    synchronized public void insertID() throws InterruptedException {
        while (this.threadID != 0) {
            wait();
        }

        this.threadID = Thread.currentThread().getId();
        notify();
    }

    synchronized public long getID() throws InterruptedException {
        while (this.threadID == 0) {
            wait();
        }

        long res = this.threadID;
        this.threadID = 0;
        notify();

        return res;
    }
}

非常感谢你!我知道了,但没用!我要发布正确的代码…谢谢朋友