同步块内的IllegalMonitorStateException

1 java multithreading runtime-error illegalmonitorstateexcep

虽然我已经在synchronized块中写了等待.我到了IllegalMonitorStateException.那是什么原因呢?

package trials;

public class WaitNotifyTrial {

    public static void main(String[] args){
        Generator g=new Generator();
        g.start();
        System.out.println("Start");
        synchronized (g) {
                try {
                    g.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    System.out.println("Printing exception");
                    e.printStackTrace();
                }
                System.out.println(g.value);
        }
    }
}

class Generator extends Thread{

    int value;

    public void run(){
        synchronized (this) {
            value=10;
        }
        notify();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*nik 6

这些是您的代码有些问题:

  • 你打电话notify()到外面synchronized (this)(这是你的直接问题);
  • 你没有使用正确的等待循环习惯用法,因此面对虚假的唤醒错过的通知会冒着不确定行为/死锁的风险;
  • wait-notifyThread实例上使用该机制,建议在其文档中使用该机制;
  • 你扩展Thread而不是按原样使用该类,只传递它的实现实例Runnable.

现在差不多整整十年了,一般的建议是wait-notify完全避免这种机制,而是使用同步辅助之一java.util.concurrent,例如CountDownLatch.