AtomicInteger类

一、概念:AtomicInteger(atomic:原子的意思)

AtomicInteger类是系统底层保护的int类型,通过提供执行方法的控制进行值的原子操作。AtomicInteger它不能当作Integer来使用

从JAVA 1.5开始,AtomicInteger 属于java.util.concurrent.atomic 包下的一个类。

二、作用:

  1. 支持原子操作的Integer类
  2. 主要用于在高并发环境下的高效程序处理。使用非阻塞算法(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
         
    }
}

​

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值