并发编程 - AtomicReference 初次接触

项目上用到非阻塞原子性AtomicReference实体记录一下

1、 AtomicReference的基本用法

1.2、创建 AtomicReference

AtomicReference是一个泛型类,它的构造与其他原子类型的构造一样,也提供了无参和一个有参的构造函数。

AtomicReference():当使用无参构造函数创建AtomicReference对象的时候,需要再次调用set()方法为AtomicReference内部的value指定初始值。
AtomicReference(V initialValue):创建AtomicReference对象时顺便指定初始值。

1.3、常用方法

  • compareAndSet(V expect, V update):原子性地更新AtomicReference内部的value值,其中expect代表当前AtomicReference的value值,update则是需要设置的新引用值。该方法会返回一个boolean的结果,当expect和AtomicReference的当前值不相等时,修改会失败,返回值为false,若修改成功则会返回true。
  • getAndSet(V newValue):原子性地更新AtomicReference内部的value值,并且返回AtomicReference的旧值。
  • getAndUpdate(UnaryOperator updateFunction):原子性地更新value值,并且返回AtomicReference的旧值,该方法需要传入一个Function接口。
  • updateAndGet(UnaryOperator updateFunction):原子性地更新value值,并且返回AtomicReference更新后的新值,该方法需要传入一个Function接口。
  • getAndAccumulate(V x, BinaryOperator accumulatorFunction):原子性地更新value值,并且返回AtomicReference更新前的旧值。该方法需要传入两个参数,第一个是更新后的新值,第二个是BinaryOperator接口。
  • getAndAccumulate(V x, BinaryOperator accumulatorFunction):原子性地更新value值,并且返回AtomicReference更新前的旧值。该方法需要传入两个参数,第一个是更新后的新值,第二个是BinaryOperator接口。
  • accumulateAndGet(V x, BinaryOperator accumulatorFunction):原子性地更新value值,并且返回AtomicReference更新后的值。该方法需要传入两个参数,第一个是更新的新值,第二个是BinaryOperator接口。
  • get():获取AtomicReference的当前对象引用值。
  • set(V newValue):设置AtomicReference最新的对象引用值,该新值的更新对其他线程立即可见。
    lazySet(V newValue):设置AtomicReference的对象引用值。lazySet方法的原理已经在AtomicInteger中介绍过了,这里不再赘述。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值