Why does notifyAll() raise IllegalMonitorStateException when synchronized on Integer?

后端 未结 4 1053
情书的邮戳
情书的邮戳 2020-12-08 09:30

Why does this test program result in a java.lang.IllegalMonitorStateException?

public class test {
    static Integer foo = new Integer(1);
             


        
4条回答
  •  情话喂你
    2020-12-08 09:59

    Incrementing the Integer makes the old foo disappear and be replaced with a brand new object foo which is not synchronized with the previous foo variable.

    Here is an implementation of AtomicInteger that erickson suggested above. In this example foo.notifyAll(); does not produce a java.lang.IllegalMonitorStateException beause the AtomicInteger Object is not refreshed when foo.incrementAndGet(); is run.

    import java.util.concurrent.atomic.AtomicInteger;
    
    public class SynchronizeOnAPrimitive {
        static AtomicInteger foo = new AtomicInteger(1);
        public static void main(String[] args) {
            synchronized (foo) {
                foo.incrementAndGet();
                foo.notifyAll();
            }
            System.out.println("foo is: " + foo);
        }
    }
    

    Output:

    foo is: 2
    

提交回复
热议问题