通过 this vs dummy 对象同步 [英] synchronizing by this vs dummy object

查看:38
本文介绍了通过 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++;
    }
}

推荐答案

这正是锁对象的重点——你可以为不同的操作使用不同的锁.假设同时运行 addAaddB 是有意义的(并且从外观上看 - 它确实如此),您确实应该有两个单独的锁,每个方法一个.

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 对象同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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