简体   繁体   English

多线程锁方法

[英]Multi threading lock methods

Ex 1)例 1)

public void addName(String name) {
    synchronized(this) {
        lastName = name;
        nameCount++;
    }
    nameList.add(name);
}

Ex 2)例 2)

public class MsLunch {
    private long c1 = 0;
    private long c2 = 0;
    private Object lock1 = new Object();
    private Object lock2 = new Object();

    public void inc1() {
        synchronized(lock1) {
            c1++;
        }
    }

    public void inc2() {
        synchronized(lock2) {
            c2++;
        }
    }
}

I got these two java code from java website but I don't clearly see the difference between these two.我从 java 网站获得了这两个 java 代码,但我不清楚这两者之间的区别。 Could you guys give more explanation which case I should use this interchangeably?你们能否给出更多解释我应该互换使用哪种情况? Thanks in advance提前致谢

There are two differences:有两个区别:

  • The first example locks on this instead of a private reference.第一个示例锁定this而不是私有引用。 I view this as a bad idea in general - it means other code could also lock on the same monitor, which makes it harder to reason about your code.我一般认为这是一个坏主意——这意味着其他代码可能锁定在同一个监视器上,这使得你的代码更难推理。 Unless you want other code to be able to acquire a lock on the same monitor (in which case I'd usually expose a monitor explicitly for that purpose), why put yourself at the mercy of other code?除非您希望其他代码能够在同一监视器上获得锁定(在这种情况下,我通常会为此目的显式公开监视器),为什么要让自己受制于其他代码呢? The lock should be an implementation detail in most cases, but making it a public reference (which this is effectively) makes that implementation detail visible to the world.在大多数情况下,锁应该是一个实现细节,但将其设为公共引用( this很有效)会使该实现细节对世界可见。
  • The second example shows two methods within the same class locking on different references.第二个示例显示了在同一 class 中锁定不同引用的两种方法。 That means two threads could call inc1 and inc2 concurrently.这意味着两个线程可以同时调用inc1inc2 If there were multiple methods in the first example, all locking on this , then only one thread could enter any of those methods at a time.如果第一个示例中有多个方法,所有方法都锁定在this上,那么一次只有一个线程可以进入这些方法中的任何一个。

I typically use a single lock for everything within a single class unless I have good reason to believe that there are going to be lots of independent operations working on only part of the state of the class - in which case that suggests the class may be too big to start with. I typically use a single lock for everything within a single class unless I have good reason to believe that there are going to be lots of independent operations working on only part of the state of the class - in which case that suggests the class may be too大开始。

I also make my "lock variables" final, as you pretty much never want to be able to change them during the lifetime of an object.我还将我的“锁定变量”设为最终变量,因为您几乎不想在object的生命周期内更改它们。

So if I really wanted to use locks, I'd probably end up writing the second example as:因此,如果我真的想使用锁,我可能最终会将第二个示例编写为:

public class MsLunch {
    private long c1 = 0;
    private long c2 = 0;
    private final Object lock = new Object();

    public void inc1() {
        synchronized(lock) {
            c1++;
        }
    }

    public void inc2() {
        synchronized(lock) {
            c2++;
        }
    }
}

However, I'd also consider:但是,我也会考虑:

  • Not making the instance methods thread-safe to start with.不使实例方法从线程安全开始。 I find it's relatively rare that a single instance of a class will be used from multiple threads concurrently.我发现从多个线程同时使用 class 的单个实例是相对罕见的。 (Static methods should usually be thread-safe though.) (静态方法通常应该是线程安全的。)
  • Using AtomicLong instead of locking.使用AtomicLong而不是锁定。 Often using a higher-level concept instead of threading primitives can make your code simpler to understand and more efficient.通常使用更高级别的概念而不是线程原语可以使您的代码更易于理解更高效。

In the first example you are synchronizing on the this object (the actual class object. This is sufficient in most cases, consider it a coarse grain lock.在第一个示例中,您在this object(实际的 class object 上进行同步。这在大多数情况下就足够了,将其视为粗粒度锁。

In the second example you are locking on created objects with the sole purpose of locking.在第二个示例中,您锁定创建的对象的唯一目的是锁定。 This approach allows you to have finer grain of control on the locking (in this situation there are two locks going at the same time, the class object doesn't get locked up)这种方法允许您对锁定进行更精细的控制(在这种情况下,有两个锁同时运行,class object 不会被锁定)

Additionally if you synchronize a method it is pretty much the same as synchronizing on the this object.此外,如果您synchronize一个方法,它与在this object 上同步几乎相同。 Basically they are interchangeable, but you might prefer one based on your situation with lock control.基本上它们是可以互换的,但您可能更喜欢一个基于您的锁定控制情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM