synchronize(this) vs synchronize(MyClass.class)(同步(这个)与同步(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.class
和 this
是不同的东西,它们是对不同对象的不同引用.
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.
这些同步块的不同之处在于,第一个将同步所有具体处理 MyClass
的 this 实例的线程,第二个将同步 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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:同步(这个)与同步(MyClass.class)
基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01