简体   繁体   中英

This Code can Throw an IllegalMonitorStateException

void waitForSignal(){
    Object ob =new Object();

    synchronized (Thred.currentThread()) {
        try {
            ob.wait();
            ob.notify();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

This Methods Throws an IllegalMonitorStateException. Can some one explain why so.

Thanks in advance

You should only invoke wait on the object that you have acquired lock on.

In your code, you have acquried lock on Thread.currentThread() , but you are invoking it on ob , which will throw IllegalMonitorStateException .

So, you should rather change your synchronized block to: -

synchronized (ob) {

}

You want to synchronize on the object you are waiting:

synchronized (ob) {
        try {
            ob.wait();
            ob.notify();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

If even you fixed your problem with IllegalMonitorException like

void waitForSignal() {
    Object ob = new Object();
    synchronized (ob) {

your code won't work. In your code each thread creates a new lock, invisible outside the method. No chance for other threads to notify waiting threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM