IllegalMonitorStateException on notify() when synchronized on an Integer

后端 未结 1 540
难免孤独
难免孤独 2020-12-07 05:27

I\'m new to using wait() and notify() in Java and I\'m getting an IllegalMonitorStateException.

Main Code

public class ThreadTest          


        
相关标签:
1条回答
  • 2020-12-07 05:42

    This

    private static Integer state = 0;
    

    is equivalent to

    private static Integer state = Integer.valueOf(0);
    

    The invocation of valueOf(0) returns a reference to an Integer object, call it A.

    You then do

    synchronized(state) {
    

    your thread acquires the lock on the object referenced by state, currently that is A.

    You then do

    state = 1;
    

    which is equivalent to

    state = Integer.valueOf(1);
    

    which gives you a different reference to an Integer object, call it B, and assigns it to state. When you then call

    state.notify();
    

    you're invoking notify() on an object, B, for which your thread doesn't own the monitor. You can't call notify or wait on objects for which your thread doesn't own the monitor.

    0 讨论(0)
提交回复
热议问题