【发布时间】:2013-03-23 19:23:32
【问题描述】:
我正在研究 Java 多线程。我对 C/C++ pthreads 非常熟悉,但在使用 Java notify() 和 wait() 函数时遇到了问题。
我知道只有在不“拥有”(又名未同步)的线程调用通知/等待时才会抛出 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)看来,在 Integer 上同步似乎不是一个好主意,因为很难确保您在同一个实例上同步。由于我正在同步的整数是全局可见静态整数,为什么我会得到不同的实例?
【问题讨论】:
-
只是另一个提示,因为它已经被回答了:尝试将通知器设置为最终。它不会编译,因为您为通知程序分配了不同的值(对象)。
标签: java multithreading