天天看點

java.lang.IllegalMonitorStateException 異常 解析

[size=medium]首先看下官方的解釋:

void notify()

喚醒在此對象螢幕上等待的單個線程。

void notifyAll()

喚醒在此對象螢幕上等待的所有線程。

void wait()

導緻目前的線程等待,直到其他線程調用此對象的 notify() 方法或 notifyAll() 方法。

下面是一段執行個體:

[/size]

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

	@Override
	public  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 2
		while(name == null){
			System.out.println("before");
			oo.await();
		}
		System.out.println(name);
	}

}
           

[size=medium]

[color=red]注意上面的 wait() 和 notify()/notifyAll() 必須在調用同一個執行個體對象的。

因為在統一執行個體對象之間這兩個方法才是相關聯的,wait()方法執行後,通過notify()/notifyAll()才能喚醒wait()方法。[/color][/size]