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 对象同步


- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 转换 ldap 日期 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 获取数字的最后一位 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01