Question about Java synchronized

后端 未结 7 1549
小蘑菇
小蘑菇 2020-12-01 06:53

The Java documentation says that \"it is not possible for two invocations of synchronized methods on the same object to interleave\". What I need to know is whether synchro

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 07:22

    Not unless the method is static. A synchronized non-static method takes a lock on the object (instance) on which it is invoked, not on the class.

    A synchronized static method takes a lock on the class, so that could help - but it's often not very practical.

    What you could do is have a static member object in your class, and do a synchronized block on that (class-global) object in your process method.

提交回复
热议问题