关于notifyAll的IllegalMonitorStateException

时间:2016-01-08 00:53:27

标签: java concurrency

我无法理解为什么我在以下代码中在notifyAll上收到IllegalMonitorStateException。如果我查看jconsole,我看到wakeUp()中的synchronized块拥有锁。这是预期的,因为printMessage中的wait()将根据定义放弃锁定。

有人有什么想法吗?

public class Test {

private Long elapsedMillis=0l;

public void printMessage() {

    synchronized(elapsedMillis) {
       while(elapsedMillis == 0) {
            System.out.println("Pausing inside print message");
            try {
                elapsedMillis.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    System.out.println("printMessage: "+elapsedMillis);
}

public void wakeUp() {

    synchronized(elapsedMillis) {
        System.out.println("Inside wake up synchronized block");
        elapsedMillis = 99999999l;
        System.out.println("Set elapsed time and notifying");
        System.out.println("value inside wakeup "+elapsedMillis);
        elapsedMillis.notifyAll();
    }
}

public static void main(String[] args) throws InterruptedException {

    final Test test = new Test();

    Thread printThread = new Thread() {
        public void run() {
            test.printMessage();
        }
    };

    Thread wakeupThread = new Thread() {
        public void run() {
            test.wakeUp();
        }
    };

    printThread.setName("printThread");
    wakeupThread.setName("wakeupThread");

    printThread.start();
    Thread.sleep(5000);
    wakeupThread.start();
}

}

java.lang.IllegalMonitorStateException     at java.lang.Object.notifyAll(Native Method)

0 个答案:

没有答案