简体   繁体   English

此代码可以引发IllegalMonitorStateException

[英]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. 此方法引发IllegalMonitorStateException。 Can some one explain why so. 有人可以解释为什么。

Thanks in advance 提前致谢

You should only invoke wait on the object that you have acquired lock on. 您应该仅对已获得锁定的对象调用wait

In your code, you have acquried lock on Thread.currentThread() , but you are invoking it on ob , which will throw IllegalMonitorStateException . 在您的代码中,您已经获得Thread.currentThread()锁定,但是您正在ob上调用它,这将引发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 如果您甚至通过IllegalMonitorException解决了问题,例如

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. 其他线程没有机会通知正在等待的线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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