synchronize(this) vs synchronize(MyClass.class) [duplicate]

这一生的挚爱 提交于 2019-11-27 13:36:06

问题


Possible Duplicate:
Java Synchronized Block for .class

I was reading through an article on synchronization. I am confused on below points and need more clarification

1) For synchronization block. How

   synchronize(this){
    // code
   }

differs from

   synchronize(MyClass.class){
    //code
   }

2) Synchronizing instance method means threads will have to get exclusive lock on the instance, while synchronizing static method means thread will have to acquire a lock on whole class(correct me if I am wrong). So if a class has three methods and one of them is static synchronized then if a thread acquires lock on that method then that means it will acquire lock on the whole class. So does that mean the other two will also get locked and no other method will be able to access those two methods as the whole class is having lock?


回答1:


MyClass.class and this are different things, are different references to different objects.

this - is the reference to particular this instance of class, and

MyClass.class - is the reference to MyClass description object.

This synchronization blocks differs in that the first will synchronize all threads that deal concretely with this instance of MyClass, and the second one will synchronize all threads independently of which object on which this method was called.




回答2:


The first example (acquiring lock on this) is meant to be used in instance methods, the second one (acquiring lock on class object) -- in static methods.

If one thread acquires lock on MyClass.class, other threads will have to wait to enter the synchronized block of a static method that this block is located in. Meanwhile, all of the threads will be able to acquire lock for a particular instance of this class and execute instance methods.



来源:https://stackoverflow.com/questions/14495776/synchronizethis-vs-synchronizemyclass-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!