AtomicInteger
属于java.util.concurrent.atomic 包下的一个类。
AtomicInteger
设置值获取值AtomicInteger
通过调用构造函数可以直接创建。在AtomicInteger
提供了两种方法来获取和设置它的实例的值
//初始值是 0
AtomicInteger atomicInteger = new AtomicInteger();
//初始值是 100
AtomicInteger atomicInteger = new AtomicInteger(100);
int currentValue = atomicInteger.get(); //100
atomicInteger.set(1234); //当前值1234
AtomicInteger
两种情况:
AtomicInteger
class提供了一些以原子方式执行加法和减法操作的方法。
addAndGet()
- 以原子方式将给定值添加到当前值,并在添加后返回新值。getAndAdd()
- 以原子方式将给定值添加到当前值并返回旧值。incrementAndGet()
- 以原子方式将当前值递增1并在递增后返回新值。它相当于i ++操作。getAndIncrement()
- 以原子方式递增当前值并返回旧值。它相当于++ i操作。decrementAndGet()
- 原子地将当前值减1并在减量后返回新值。它等同于i-操作。getAndDecrement()
- 以原子方式递减当前值并返回旧值。它相当于-i操作。public class Main
{
public static void main(String[] args)
{
AtomicInteger atomicInteger = new AtomicInteger(100);
System.out.println(atomicInteger.addAndGet(2)); //102
System.out.println(atomicInteger); //102
System.out.println(atomicInteger.getAndAdd(2)); //102
System.out.println(atomicInteger); //104
System.out.println(atomicInteger.incrementAndGet()); //105
System.out.println(atomicInteger); //105
System.out.println(atomicInteger.getAndIncrement()); //105
System.out.println(atomicInteger); //106
System.out.println(atomicInteger.decrementAndGet()); //105
System.out.println(atomicInteger); //105
System.out.println(atomicInteger.getAndDecrement()); //105
System.out.println(atomicInteger); //104
}
}
current value == the expected value
。
boolean compareAndSet(int expect, int update)
我们可以compareAndSet()
在Java并发集合类中看到amy实时使用方法ConcurrentHashMap
。
import java.util.concurrent.atomic.AtomicInteger;
public class Main
{
public static void main(String[] args)
{
AtomicInteger atomicInteger = new AtomicInteger(100);
boolean isSuccess = atomicInteger.compareAndSet(100,110); //current value 100
System.out.println(isSuccess); //true
isSuccess = atomicInteger.compareAndSet(100,120); //current value 110
System.out.println(isSuccess); //false
}
}
程序输出
true
false
AtomicInteger
是当我们处于多线程上下文时,我们需要在不使用关键字的情况下对值执行原子操作。int
synchronized
AtomicInteger
与使用同步执行相同操作相比,使用它同样更快,更易读。https://www.leftso.com/article/568.html