且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java以单例模式同步

更新时间:2023-12-03 13:54:58

这就像其他任何一样类。它可能需要或可能不需要进一步同步。

It's just like any other class. It may or may not need further synchronization.

请考虑以下示例:

public class Singleton {

  private Singleton() {}

  public synchronized static Singleton getInstance() { ... }

  private int counter = 0;

  public void addToCounter(int val) {
    counter += val;
  }
}

如果要从多个线程使用该类, addToCounter()有竞争条件。解决这个问题的一种方法是使 addToCounter()同步:

If the class is to be used from multiple threads, addToCounter() has a race condition. One way to fix that is by making addToCounter() synchronized:

  public synchronized void addToCounter(int val) {
    count += val;
  }

还有其他方法可以修复竞争条件,例如使用 AtomicInteger

There are other ways to fix the race condition, for example by using AtomicInteger:

  private final AtomicInteger counter = new AtomicInteger(0);

  public void addToCounter(int val) {
    counter.addAndGet(val);
  }

在这里,我们已经修复了竞争条件而没有使用 synchronized

Here, we've fixed the race condition without using synchronized.