一、概念:AtomicInteger(atomic:原子的意思)
AtomicInteger类是系统底层保护的int类型,通过提供执行方法的控制进行值的原子操作。AtomicInteger它不能当作Integer来使用
从JAVA 1.5开始,AtomicInteger 属于java.util.concurrent.atomic 包下的一个类。
二、作用:
- 支持原子操作的Integer类
- 主要用于在高并发环境下的高效程序处理。使用非阻塞算法(CAS实现线程的安全)来实现并发控制。
附:CAS(compare and swap)比较并交换,多用于修改密码等
三、用法
1.创建Atomicnteger
//初始值是 0
AtomicInteger atomicInteger = new AtomicInteger();
//初始值是 100
AtomicInteger atomicInteger = new AtomicInteger(100);
int currentValue = atomicInteger.get(); //100
atomicInteger.set(1234); //当前值1234
2.方法:
基本方法:
addAndGet() 添加当前值后返回新值。
getAndAdd() 添加到当前值并返回旧值。
incrementAndGet() 将当前值递增1并在递增后返回新值。它相当于i ++操作。
getAndIncrement() 递增当前值并返回旧值。它相当于++ i操作。
decrementAndGet() 当前值减1并在减量后返回新值。它等同于i-操作。
getAndDecrement() 递减当前值并返回旧值。它相当于-i操作。
重要方法:
1、比较和交换操作将内存位置的内容与给定值进行比较,并且只有它们相同时,才将该内存位置的内容修改为给定的新值。这是作为单个原子操作完成的。
2、原子性保证了新值是根据最新信息计算出来的; 如果在此期间该值已被另一个线程更新,则写入将失败。
为了支持比较和交换操作,此类提供了一种方法,如果将该值原子地设置为给定的更新值current value == the expected value
boolean compareAndSet(int expect, int update)
例:
import java.util.concurrent.atomic.AtomicInteger;
public class Main{
public static void main(String[] args){
//1、默认初始值
AtomicInteger atomicInteger = new AtomicInteger(1);
//2、默认初始值和给定值,都是1,所以会更改成功
boolean isSuccess = atomicInteger.compareAndSet(1,5); //atomicInteger 变为 5
//3、返回true
System.out.println(isSuccess); //true
//4、atomicInteger 的值变为5,给定值是1,所以会更改失败
isSuccess = atomicInteger.compareAndSet(1,10); //atomicInteger 还是为 5
//5、返回false
System.out.println(isSuccess); //false
}
}