简介:java.util.concurrent(JUC)有个atomic小型工具包,支持单个变量上的无锁线程安全编程。
以上是这个包下的所有相关类,java.util.concurrent.atomic.AtomicLong类只是其中的一种,提供了可以被原子地读取和写入的底层long值的操作,并且还包含高级原子操作。下面我们一来学习这个类的方法及用途。
方法:
示例:
以下AtomicLongTest程序显示了在基于线程的环境中使用AtomicLong的计数器的安全实现,帮助我们更好的理解为什么使用。
import java.util.concurrent.atomic.AtomicLong;
public class AtomicLongTest {
static class Counter{
//AtomicLong
private AtomicLong a = new AtomicLong(0);
//long
private long num=0;
public void increment(){
a.getAndIncrement();
}
public long value(){
return a.get();
}
}
public static void main(String[] args) throws InterruptedException {
final Counter counter = new Counter();
//1000 threads
for (int i = 0; i < 1000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
counter.increment();
counter.num++;
}
}).start();
}
Thread.sleep(6000);
System.out.println("Final number (should be 1000): " + counter.value());
System.out.println("Final long (not 1000): " + counter.num);
}
}
结果:
多次运行,我们会发现AtomicLong值始终是100,long值却不一定,由此可见AtomicLong类保证了并发下数值的一致性。为什么AtomicLong可以呢,看下他的源码实现
由此可见,AtomicInteger.getAndIncrement()的实现用了乐观锁技术,调用了类sun.misc.Unsafe库里面的 CAS算法,用CPU指令来实现无锁自增。synchronized关键字的独占锁相比,效率会高很多。看到这里引出了一个很核心的东西- CAS算法。
附上文章链接-什么是CAS算法