我正在進入Java多線程。我對C/C++ pthreads非常熟悉,但是遇到了Java notify()
和wait()
函數的問題。爲什麼會拋出IllegalMonitorStateException?
據我所知,IllegalMoinitorStateException
只有當一個線程不「擁有」(又名未經同步)調用通知/等待。
當寫我的申請,我就遇到了這個問題。我分離下面的測試代碼的問題:
public class HelloWorld
{
public static Integer notifier = 0;
public static void main(String[] args){
notifier = 100;
Thread thread = new Thread(new Runnable(){
public void run(){
synchronized (notifier){
System.out.println("Notifier is: " + notifier + " waiting");
try{
notifier.wait();
System.out.println("Awake, notifier is " + notifier);
}
catch (InterruptedException e){e.printStackTrace();}
}
}});
thread.start();
try{
Thread.sleep(1000);
}
catch (InterruptedException e){
e.printStackTrace();
}
synchronized (notifier){
notifier = 50;
System.out.println("Notifier is: " + notifier + " notifying");
notifier.notify();
}
}
}
此輸出:
Exception in thread "main" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at HelloWorld.main(HelloWorld.java:27)
相信我已經獲取的通知對象的鎖。我究竟做錯了什麼?
謝謝!
編輯:
從這個可能重複(Synchronizing on an Integer value),它似乎不是在整型同步,因爲這是很難確保你是在同一個實例進行同步是個好主意。因爲我正在同步的整數是全局可見的靜態整數,爲什麼我得到不同的實例?
可能重複:HTTP://stackoverflow.com/questions/659915/synchronizing-on-an-integer-value – Cratylus 2013-03-23 19:26:59
又一個暗示,因爲它已經有了答案:嘗試將通知設置爲最終。由於您爲通知程序指定了不同的值(對象),因此它不會編譯。 – 2013-03-23 20:07:11