如何增加AtomicInteger两次?

时间:2017-05-10 11:43:27

标签: java thread-safety java.util.concurrent

我需要两次增加AtomicInteger,例如: ++ I; ++ I; 通过无尽的ciycle,我想增加计数器两次并在奇偶校验上检查它。 但我总是得到一次递增的变量。怎么解决?

2 个答案:

答案 0 :(得分:3)

    AtomicInteger counter = new AtomicInteger(100);
    counter.addAndGet(2);
    System.out.println(counter);

    AtomicInteger counter = new AtomicInteger(100);        
    counter.incrementAndGet();
    counter.incrementAndGet();
    System.out.println(counter);

答案 1 :(得分:0)

每次都给我一个偶数:

import java.util.concurrent.atomic.AtomicInteger;

public class HelloWorld {
  public static void main(String[] args) {
        AtomicInteger counter = new AtomicInteger(100);
        int limit = 100;
        while ( limit-- != 0 ){
            counter.incrementAndGet();
            counter.incrementAndGet();
            System.out.println(counter.get());
        }
  }
}