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

查看:28
本文介绍了同步(这个)与同步(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 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?

推荐答案

MyClass.classthis 是不同的东西,它们是对不同对象的不同引用.

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

this - 是对该类的这个特定实例的引用,并且

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

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

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

这些同步块的不同之处在于,第一个将同步所有具体处理 MyClassthis 实例的线程,第二个将同步 all 线程独立于调用哪个方法的对象.

These synchronization blocks differ 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 method was called.

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

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