先查看源码:
/**
* Thrown to indicate that a thread has attempted to wait on an
* object's monitor or to notify other threads waiting on an object's
* monitor without owning the specified monitor.
* 抛出该异常表明某一线程已经试图等待对象的监视器,或者试图通知其他正在等待对象的监视器,然而本身没有指定的监视器的线程。
*
* @author unascribed
* @see java.lang.Object#notify()
* @see java.lang.Object#notifyAll()
* @see java.lang.Object#wait()
* @see java.lang.Object#wait(long)
* @see java.lang.Object#wait(long, int)
* @since JDK1.0
*/
public
class IllegalMonitorStateException extends RuntimeException {
private static final long serialVersionUID = 3713306369498869069L;
/**
* Constructs an <code>IllegalMonitorStateException</code> with no
* detail message.
*/
public IllegalMonitorStateException() {
super();
}
/**
* Constructs an <code>IllegalMonitorStateException</code> with the
* specified detail message.
*
* @param s the detail message.
*/
public IllegalMonitorStateException(String s) {
super(s);
}
}
当前的线程不是此对象监视器的所有者。当前线程要锁定该对象之后,才能用锁定的对象执行这些方法,这里需要用到synchronized关键字,锁定哪个对象就用哪个对象来执行notify(), notifyAll(),wait(), wait(long), wait(long, int)操作,否则就会报IllegalMonitorStateException异常
public void waitKm(){
try {
//这里synchronized锁的那个对象就用那个对象调用wait()方法,其他方法同理
synchronized (obj) {
obj.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}