Java API 之 AtomicLong

一、atomic

我们在使用变量的时候,经常会出现资源竞争的情况,为了保证变量安全,我们就会对对应的方法添加"synchronized"同步锁来达到目的,以保证线程安全。

而JDK在1.5已经开始提供了一些原子类,在:java.util.concurrent.atomic软件包下

这个包下提供了对int、long、array等的原子操作,简单来说,我们不再需要去对方法增加同步锁来保证线程安全,因为这些原子类的操作本身即是线程安全的。

二、AtomicLong

以下,AtomicLong为例:

java.util.concurrent.atomic.AtomicLong类

直接继承于Number类

这表明,使用它就像使用Number类一样简单,它就像是一个基本类型的包装类

1)初始化一个值

// 默认初始值为0
public AtomicLong atomicLong = new AtomicLong();
// 也可以赋值
public AtomicLong atomicLong = new AtomicLong(10L);

2)加

// 返回更新的值
atomicLong.addAndGet(1L)
// 返回更新前的值
atomicLong.getAndAdd(1L)

3)自增

// 自增,返回更新的值
atomicLong.incrementAndGet();
// 自增,返回旧的值
atomicLong.getAndIncrement()

4)自减

// 自减,返回更新的值
atomicLong.decrementAndGet();
// 自减,返回旧的值
atomicLong.getAndDecrement();

5)设置值

// 设置值
atomicLong.set(10L);
// 最后设定为给定值
atomicLong.lazySet(10L);
// 设置值,返回旧值
atomicLong.getAndSet(2L);
// 如果当前值 == 预期的值 那么设置为给定值
atomicLong.compareAndSet(1L, 2L);
// 如果当前值 == 预期的值 那么设置为给定值
atomicLong.weakCompareAndSet(1L, 2L);

6)类型转换

// 返回double
atomicLong.doubleValue();
// 返回float
atomicLong.floatValue();
// 返回int
atomicLong.intValue();
// 返回long
atomicLong.longValue();
// 转换为字符串
atomicLong.toString();

7)获取当前值

atomicLong.get()

更多详细内容参考JDK文档:http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/concurrent/atomic/AtomicLong.html#weakCompareAndSet(long,%20long)

猜你喜欢

转载自www.cnblogs.com/lay2017/p/9066719.html
今日推荐