java的wait和notify以及IllegalMonitorStateException



java的wait和notify以及IllegalMonitorStateException

 

在notify和wait方法的java api文档里,都有这句话: This method should only be called by a thread that is the owner of this object’s monitor. 在notify方法的文档说明里写了如何让当前线程成为这个对像的监视器,如下:
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. 说白了对wait和notify使用的时候,要不报IllegalMonitorStateException错误,最简单的就是要在使用前,对那个对像要使用synchronized,如: Object obj = new Object(); synchronized(obj){obj.wait();} synchronized(obj){obj.notify();} 不然无论是在调用wait还是nofity的时候都会报IllegalMonitorStateException错误。