Why Java throw java.lang.IllegalMonitorStateException when I invoke wait() in static way synchronized block?

谁说胖子不能爱 提交于 2021-01-18 10:54:32

问题


I do not understand why Java throw exception from subject in this code. Could somebody explain me it?

class Wait implements Runnable
{
    public void run() {
        synchronized (Object.class) {
            try {
                while(true) {
                    System.out.println("Before wait()");
                    wait();
                    System.out.println("After wait()");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class ObjectMethodInConcurency 
{
    public static void main(String[] args) {
        Wait w = new Wait();
        (new Thread(w)).start();
    }
}

回答1:


Use synchronized (this) { instead of synchronized (Object.class) in your class

EDIT

Reasoning behind the IllegalMonitorException in above code

In Java using synchronized keyword is a way to create and obtain a monitor object which will be used as lock to execute corresponding code block.

In the above code that monitor is "Object.class".

And wait() method tells the current thread to wait until it is notifyed and you have to invoke wait() on the monitor object which owns the lock.

So the way to invoke wait() method is like below otherwise you will get IllegalMonitorException.

synchronized(monitor){
    monitor.wait();
}

So for your example you can either use "Object.class.wait()" or change the monitor to this since you are calling wait() method on the current instance



来源:https://stackoverflow.com/questions/21149139/why-java-throw-java-lang-illegalmonitorstateexception-when-i-invoke-wait-in-st

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!