您的位置 首页 java

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();  

上述例子创建了初始值为0的AtomicLong ,如果需要创建指定值的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.

比较设置(CAS)AtomicLong的值

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));  

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

AtomicLong减法

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

  • decrementAndGet()
  • getAndDecrement()

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

参考:

文章来源:智云一二三科技

文章标题:JAVA并发-AtomicLong

文章地址:https://www.zhihuclub.com/183660.shtml

关于作者: 智云科技

热门文章

发表回复

您的电子邮箱地址不会被公开。

网站地图