简体   繁体   English

是否可以使用带有两个AtomicInteger的线程安全方法?

[英]Is a Thread-safe method with two AtomicIntegers possible?

I want to write a Thread-safe method sum() but I'm not sure if I can use two AtomicIntegers to make it safe or do I have to use a synchronized block? 我想编写一个线程安全的方法sum(),但不确定是否可以使用两个AtomicIntegers使其安全,还是必须使用同步块?

class A {

   private AtomicInteger a = new AtomicInteger();
   private AtomicInteger b = new AtomicInteger();

   public void sum(int c) {
      a.set(a.get() + b.get() + c);
   }
}

The rules for evaluation order in Java mean that you'll always follow a series of non-overlapping locks: A (get) -> B (get) -> A (set). Java中评估顺序的规则意味着您将始终遵循一系列不重叠的锁:A(获取)-> B(获取)-> A(集合)。 So you won't have any issues with blocking, because the locks won't interfere with one another. 这样您就不会有任何阻塞问题,因为锁不会互相干扰。 Note that there is, however, a form of race condition: it is possible for thread 1 to read A, then read B. Before thread 1 sets A, thread 2 can read A and B. The final value will be one of the threads' resulting sum, but the other will be lost. 但是请注意,存在一种竞争条件:线程1可能先读取A,然后读取B。在线程1设置A之前,线程2可以读取A和B。最终值将是线程之一产生的总和,但另一个将丢失。

There are specific methods of AntomicInteger to take care of this. 有AntomicInteger的特定方法可以解决此问题。 You don't need to break out of the AtomicInteger word and it's thread safety. 您不需要打破AtomicInteger这个词,它是线程安全的。 Just checking the JavaDocs of AtomicInteger will show you methods like AtomicInteger.getAndAdd that you can use for this. 只需检查AtomicInteger的JavaDocs,就会显示可用于此目的的方法,例如AtomicInteger.getAndAdd

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

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