Question about Java synchronized

后端 未结 7 1552
小蘑菇
小蘑菇 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:42

    No; synchronized only prevents multiple threads from simultaneously executing the method in the same instance. If you have n instances, there could be n threads, each executing the method in one of the instances.

    If you need to ensure that only one thread may execute the method across all instances, you should make the method static, or make the method non-synchronized and rather use a synchronized block inside the method to lock on a private static field.

    Edit: Note that synchronizing on a private instance variable is preferrable to having a synchronized method or to synchronize on this, and that locking on a private static instance variable is preferrable to having a static synchronized method or an instance method that synchronizes on this.getClass(). The reason is that this and this.getClass() are object references that are accessible throughout the program, so anybody may synchronize on these objects, and thereby block threads that want to call your method.

    Edit: Also, see @Cowan's comment below - summary: if you really want to lock on the class, you might want to use synchronized (Worker.class) rather than synchronized (this.getClass()), depending on what effect you want in the case of subclassing.

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