一、简介
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等类同