读书人

java.lang.IllegalMonitorStateExcept

发布时间: 2012-10-24 14:15:58 作者: rapoo

java.lang.IllegalMonitorStateException 异常 解析
首先看下官方的解释:
void notify()
唤醒在此对象监视器上等待的单个线程。
void notifyAll()
唤醒在此对象监视器上等待的所有线程。
void wait()
导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。

下面是一段实例:


public class OtherObject {public synchronized void await(){try {wait();} catch (InterruptedException e) {e.printStackTrace();}}public synchronized void anotify(){notifyAll();}}public class ShareDataThread implements Runnable{private static String name;/**  * wait()导致当前的线程等待,直到其他线程调用此对象(the same object  *like: OtherObject)的 notify() 方法或 notifyAll() 方法。**/private static OtherObject oo = new OtherObject();@Overridepublic  void run() {name = "simon";oo.anotify();}public static void main(String[] args){Thread t = new Thread(new ShareDataThread());t.start();//method 1/*try {t.join();} catch (InterruptedException e) {e.printStackTrace();}*///method 2while(name == null){System.out.println("before");oo.await();}System.out.println(name);}}


注意上面的 wait() 和 notify()/notifyAll() 必须在调用同一个实例对象的。
因为在统一实例对象之间这两个方法才是相关联的,wait()方法执行后,通过notify()/notifyAll()才能唤醒wait()方法。

读书人网 >编程

热点推荐