synchronized block for an Integer object

后端 未结 3 882
悲哀的现实
悲哀的现实 2020-12-02 01:14

I just came across the synchronized block in Java and wrote a small programm to test how it works.

I create 10 threads and let each thread increment an Integer objec

3条回答
  •  眼角桃花
    2020-12-02 01:58

    As assumed it is because of the immutability of the Integer object.

    I've changed the synchonized block to

    Integer old = syncObj;
    syncObj ++;
    System.out.println(syncObj == old);
    

    and my console gets filled with falses

    So each time I increment the Integer a new object is createt.

    Therefore I only read from the old Object and it will not be locked.

提交回复
热议问题