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);}}