java.lang.IllegalMonitorStateException

 代碼:

public void push() {
		while (production > 1) {
			System.out.println("請等待消費者取走." + production);
			try {
				synchronized (this) {
					wait();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		synchronized (Storage.class) {
			production++;
		}
		System.out.println("生產一個,目前庫存 " + production);
		Storage.class.notifyAll();
	}


報出了:java.lang.IllegalMonitorStateException非法檢測狀態

將wait()和notify()(或者niotifyAll)全部放入synchronized 快中就ok了。

	public void push() {
		while (production > 1) {
			System.out.println("請等待消費者取走." + production);
			try {
				synchronized (this) {
					wait();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		synchronized (Storage.class) {
			production++;
		}
		System.out.println("生產一個,目前庫存 " + production);
		synchronized (Storage.class) {
			Storage.class.notifyAll();
		}
	}


原因是如果不具備synchronized ()括號中對象的鎖標記,就不能對該對象wait()notify()操作。所以報出java.lang.IllegalMonitorStateException。所以必須把wait()notify()

都放在synchronized塊中。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章