我正在进入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