为什么会抛出IllegalMonitorStateException?

Aus*_*tin 2 java multithreading

我正在进入Java多线程.我对C/C++ pthreads非常熟悉,但是我遇到了Java notify()wait()函数的问题.

我知道IllegalMoinitorStateException只有当一个不"拥有"(又名没有同步)的线程调用notify/wait时才会抛出一个.

在编写我的应用程序时,我遇到了这个问题.我用以下测试代码隔离了问题:

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();
        }
        }
    }
Run Code Online (Sandbox Code Playgroud)

这输出:

    Exception in thread "main" java.lang.IllegalMonitorStateException
        at java.lang.Object.notify(Native Method)
        at HelloWorld.main(HelloWorld.java:27)
Run Code Online (Sandbox Code Playgroud)

我相信我已经获得了通知对象的锁定.我究竟做错了什么?

谢谢!

编辑:

从这个可能的重复(在整数值上进行同步),似乎在Integer上同步并不是一个好主意,因为很难确保您在同一个实例上进行同步.由于我正在同步的整数是一个全局可见静态整数,为什么我会得到不同的实例?

UmN*_*obe 5

因为notifier = 50;你正在呼唤notifier.notify();一个不同的对象.