通过这个与虚拟对象同步 [英] synchronizing by this vs dummy object

查看:155
本文介绍了通过这个与虚拟对象同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我已经看到了使用synchronized块,但最近我了解到使用虚拟对象更可取。我找到了与此相关的以下主题。

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,因为它们都使用它来锁定。

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使用的每个方法设置两个不同的虚拟对象? / p>

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.

这篇关于通过这个与虚拟对象同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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