多线程-原子更新类的使用

AtomicReference、AtomicIntegerFieldUpdater、等类的使用

吉林乌拉 2019-05-20 08:59:00

AtomicReference类的作用是以原子的方式更新引用类型。下面我们看一下具体的例子。

AtomicReference、AtomicIntegerFieldUpdater、等类的使用

 

AtomicReference、AtomicIntegerFieldUpdater、等类的使用

 

AtomicReference、AtomicIntegerFieldUpdater、等类的使用

 

下面我们看一下AtomicReferenceFieldUpdater类的使用,我们有时不想更新对象的所有属性,只想更新某一个字段,并且我们知道字段的返回值类型也有可能是不确定的,所以Java并发工具包里为我们提供了很多字段的更新类型。如AtomicIntegerFieldUpdater类和AtomicLongFieldUpdater类,前者就是更新Integer类型的字段后者就是更新Long类型字段的。除此之外我们还知道字段的类型还可能是引用类型,那我们就可以用AtomicReferenceFieldUpdater类来更新某一个引用类型的字段,这几个更新字段的类的使用方法几乎一样,所以下面只演示AtomicReferenceFieldUpdater类的使用,并且用String类型来演示。

AtomicReference、AtomicIntegerFieldUpdater、等类的使用

 

AtomicReference、AtomicIntegerFieldUpdater、等类的使用

 

AtomicReference、AtomicIntegerFieldUpdater、等类的使用

 

这里有二点要注意:

  • 更新的实例变量必须是volatile变量否则更新时会出异常。

AtomicReference、AtomicIntegerFieldUpdater、等类的使用

 

  • 更新的实例变量必须是public变量否则更新时会出异常。

AtomicReference、AtomicIntegerFieldUpdater、等类的使用

 

下面我们看一下AtomicIntegerFieldUpdater类的使用,它比AtomicReferenceFieldUpdater类简单了一点。

AtomicReference、AtomicIntegerFieldUpdater、等类的使用

 

AtomicReference、AtomicIntegerFieldUpdater、等类的使用

 

AtomicReference、AtomicIntegerFieldUpdater、等类的使用

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值