synchronizing by this vs dummy object(通过 this vs dummy 对象同步)
问题描述
到目前为止,我已经看到了同步块的用法,但最近我了解到使用虚拟对象更可取.我找到了与此相关的以下主题.
I have seen usage of synchronized block by this so far but recently I learned that using dummy object is preferable. I found the following topic related to this.
Java 同步方法锁定对象或方法?
总而言之,在下面的代码中,两个不同的对象不能同时运行 addA 和 addB,因为两者都使用 this 来锁定.
As a summary, in the code below, two different object can not run addA and addB concurrently as both uses this for lock.
private int a;
private int b;
public synchronized void addA(){
a++;
}
public synchronized void addB(){
b++;
}
如果我使用虚拟对象进行锁定,我会感到困惑,如果我在两种方法中使用下面的行来同步会有什么不同?因为他们仍然会有相同的锁.
I am confused if I use dummy object for lock, what will be different if I use the line below in both method to synchronize? Because still they would have same lock.
synchronized(dummyObject){
...
}
那么,我应该为每种方法使用两个不同的虚拟对象以与 sycnhronized as 一起使用,这意味着什么?
So what it means that I should have two different dummy object for each method to use with sycnhronized as?
public void addA(){
synchronized(dummyObj1){
a++;
}
}
public void addB(){
synchronized(dummyObj2){
b++;
}
}
推荐答案
这正是锁对象的重点——你可以为不同的操作使用不同的锁.假设同时运行 addA
和 addB
是有意义的(并且从外观上看 - 它确实如此),您确实应该有两个单独的锁,每个方法一个.
That is exactly the point of lock objects - you can use different locks for different operations. Assuming it makes sense to run addA
and addB
concurrently (and from the looks of it - it definitely does), you should indeed have two separate locks, one for each method.
这篇关于通过 this vs dummy 对象同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过 this vs dummy 对象同步
基础教程推荐
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01