JAVA并发-AtomicLong

AtomicLong 类提供了long类型的变量与AtomicInteger非常类似,变量可以原子写和读,同时还包括先进的原子操作例如 compareAndSet() AtomicLong 类位于java.util.concurrent.atomic 包中,全名java.util.concurrent.atomic.AtomicLong 。本文讲述JAVA8中的AtomicLong ,但是第一个版本是在Java 5中。

关于AtomicLong 设计原理可以参考 Compare and Swap

创建AtomicLong

如下代码创建 AtomicLong :

 
AtomicLong atomicLong = new AtomicLong();

上述例子创建了初始值为0AtomicLong ,如果需要创建指定值的AtomicLong ,则代码如下:

 
AtomicLong atomicLong = new AtomicLong(123);

例子中用123作为AtomicLong 构造函数的参数,意思就是AtomicLong 实例的初始值为123

获取AtomicLong 的值

可以通过 AtomicLong  get() 方法获取值,下面是代码 AtomicLong .get():

AtomicLong atomicLong = new AtomicLong(123);

long theValue = atomicLong.get();

 

设置AtomicLong的值

可以通过 AtomicLong set()方法设置值,下面是 AtomicLong .set()的例子

AtomicLong atomicLong = new AtomicLong(123);

atomicLong.set(234);

 

例子中创建了一个初始值为123 AtomicLong ,然后设置为234.

比较设置(CASAtomicLong的值

AtomicLong 类同样有原子的compareAndSet()方法,首先与AtomicLong 实例值得当前比较,如果相对这设置AtomicLong 的新值,下面AtomicLong .compareAndSet()代码:

AtomicLong atomicLong = new AtomicLong(123);

long expectedValue = 123;
long newValue      = 234;
atomicLong.compareAndSet(expectedValue, newValue);

首先创建初始值为123 AtomicLong 实例,然后当前值与期望值123比较,如果相对则设置值为234.

增加AtomicLong的值

 AtomicLong 类包含了一些增加和获取返回值的方法:

  • addAndGet()
  • getAndAdd()
  • getAndIncrement()
  • incrementAndGet()

第一个方法 addAndGet() ,增加AtomicLong 的值同时返回增加后的值,第二个方法 getAndAdd()增加值,但是返回增加之前的值,两个方法的差别看下面代码:

AtomicLong atomicLong = new AtomicLong();
System.out.println(atomicLong.getAndAdd(10));
System.out.println(atomicLong.addAndGet(10));

代码例子将为020,首先获取AtomicLong 增加10之前的值是0,然后再增加值并获取当前值是 20.同样可以通过两个方法增加负值,相当于做减法,getAndIncrement() incrementAndGet()  getAndAdd() addAndGet()的工作原理相似,只不是加1.

AtomicLong减法

 AtomicLong 类同样可以原子性的做减法,面是方法:

  • decrementAndGet()
  • getAndDecrement()

decrementAndGet()方法减1并返回减后的值,getAndDecrement()同样减1并返回减之前的值

参考:http://tutorials.jenkov.com/java-concurrency/compare-and-swap.html

http://tutorials.jenkov.com/java-util-concurrent/atomiclong.html

https://blog.csdn.net/cgsyck/article/details/107946058

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值