同步(this)vs synchronize(MyClass.class) [英] synchronize(this) vs synchronize(MyClass.class)

查看:126
本文介绍了同步(this)vs synchronize(MyClass.class)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

.class的Java同步块

我正在阅读有关同步的文章。我对以下几点感到困惑,需要更多澄清

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

1)对于同步块。如何

1) For synchronization block. How

   synchronize(this){
    // code
   }

   synchronize(MyClass.class){
    //code
   }

2 )同步实例方法意味着线程必须获得对实例的独占锁定,而同步静态方法意味着线程必须获取整个类的锁定(如果我错了,请纠正我)。因此,如果一个类有三个方法,其中一个是静态同步的,那么如果一个线程获得对该方法的锁定意味着它将获得对整个类的锁定,那么这意味着其他两个也将被锁定,没有其他方法将能够访问这两个方法,因为整个类都有锁?

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 have three methods and one of them is static synchronized then if a thread acquire lock on that method means it will acquire lock on whole class so is that means the other two will also get locked and no other method will be able to access those two methods as whole class is having lock?

推荐答案

MyClass.class 这个是不同的东西,是对不同对象的不同引用。

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

this - 是对此类实例的引用,

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

MyClass.class - 是对 MyClass 描述对象的引用。

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

这个同步块的不同之处在于第一个同步块将同步所有线程具体处理 c> MyClass 的 实例,第二个将同步所有线程,与哪个对象无关方法被称为。

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.

这篇关于同步(this)vs synchronize(MyClass.class)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆