简体   繁体   English

何时引发IllegalMonitorSttateException?

[英]When does IllegalMonitorSttateException thrown?

Object.wait(), Object.notify(), Object.notifyAll() methods throw IllegalMonitorStateException. Object.wait(),Object.notify(),Object.notifyAll()方法引发IllegalMonitorStateException。 This exception is thrown if the current thread is not the owner of this object's monitor. 如果当前线程不是此对象的监视器的所有者,则抛出此异常。 But, not getting clearity regarding that without getting object's monitor weather current thread will be able to execute wait / notify / notifyAll on any object ? 但是,如果不弄清楚对象的监视天气,当前线程将无法对任何对象执行wait / notify / notifyAll吗? O/w what are chances for illegal monitor's state ? O / w非法监控器状态有什么机会?

Thanks scottb for suggestion. 谢谢斯科特的建议。 Thanks Henno for reply. 感谢Henno的回复。 One more doubt I am getting is regarding becoming owner of object's monitor: 我越来越怀疑是否要成为对象监视器的所有者:

A thread becomes the owner of an object's monitor in one of the following ways: •By executing a synchronized instance method of that object. 线程可以通过以下方式之一成为对象监视器的所有者:•通过执行该对象的同步实例方法。 •By executing the body of a synchronized statement that synchronizes on the object. •通过执行在对象上同步的同步语句的主体。 •For objects of type Class, by executing a synchronized static method of that class. •对于类类型的对象,通过执行该类的同步静态方法。

First two statements are understood. 前两个陈述是可以理解的。 But what is fundamental with objects of type class ? 但是,类型类对象的基础是什么?

As you mention, an IllegalMonitorStateException is thrown when the current thread is not the owner of this object's monitor, ie a lock monitor. 如您所述,当当前线程不是该对象的监视器(即锁定监视器)的所有者时,将引发IllegalMonitorStateException。 This means the current thread has to call wait or notify from within a synchronized code block like: 这意味着当前线程必须在诸如以下代码的同步代码块内调用wait或notify:

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

If you only do 如果你只做

object.wait();

an IllegalMonitorStateException is thrown because the current thread hasn't obtained the object's lock by using synchronized. 抛出IllegalMonitorStateException,因为当前线程尚未通过使用同步来获取对象的锁。

If you lock on another object without having the lock monitor on the object it is also thrown: 如果锁定另一个对象而没有在该对象上具有锁定监视器,则也会引发该对象:

synchronized(object) {
    someOtherObject.wait();
}

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

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