The synchronized lock object cannot be of type Integer, String, or Long

 

Integer type:

i++ is actually i = new Integer(i+1), so after executing i++, i is no longer the original object, the object of the lock has changed, and the objects locked by multiple threads are different, so the synchronization block is naturally invalid up.

Long type: same as above

String type:

It is because the variables defined by String will be placed in the constant pool. If the values ​​of the String variables defined by multiple threads are equal, the lock will be invalid. They seem to lock different objects, but they are actually the same object. this kind of hard to find

Guess you like

Origin blog.csdn.net/u013282737/article/details/121117507