二、多线程之Atomic包

一、简介

1、原子操作

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

而原子操作时一种线程安全的操作,在操作执行期间不会穿插任何操作。这意味着,我们不需要使用synchronized等同步串行机制去控制资源的访问。

2、atomic包

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

这个包下提供了对int、long、array等的原子操作,简单来说,我们可以通过复用这些现有的类来达到线程安全的目的。

JDK文档:http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/concurrent/atomic/package-frame.html

 

二、AtomicLong

以下,AtomicLong为例:

java.util.concurrent.atomic.AtomicLong类:http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/concurrent/atomic/AtomicLong.html

直接继承于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()

我们看到以上罗列的一些操作,把很多复合操作都变成了原子操作。还有一些常用的原子类,如:AtomicInterger、AtomicReference等类同

转载于:https://www.cnblogs.com/lay2017/p/10164519.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值