atomic原子类实现机制_深入了解Java atomic原子类的使用方法和原理

本文通过实例解析了AtomicInteger在多线程环境中的线程安全特性,重点讲解了volatile关键字的作用、CAS(CompareAndSet)操作的内存模型和底层实现。展示了如何确保数据的一致性和原子性,适合学习并发编程和内存模型的同学。
摘要由CSDN通过智能技术生成

在讲atomic原子类之前先看一个小例子:

public class UseAtomic {

public static void main(String[] args) {

AtomicInteger atomicInteger=new AtomicInteger();

for(int i=0;i<10;i++){

Thread t=new Thread(new AtomicTest(atomicInteger));

t.start();

try {

t.join(0);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println(atomicInteger.get());

}

}

class AtomicTest implements Runnable{

AtomicInteger atomicInteger;

public AtomicTest(AtomicInteger atomicInteger){

this.atomicInteger=atomicInteger;

}

@Override

public void run() {

atomicInteger.addAndGet(1);

atomicInteger.addAndGet(2);

atomicInteger.addAndGet(3);

atomicInteger.addAndGet(4);

}

}

最终的输出结果为100,可见这个程序是线程安全的。如果把AtomicInteger换成变量i的话,那最终结果就不确定了。

打开AtomicInteger的源码可以看到:

// setup to use Unsafe.compareAndSwapInt for updates

private static final Unsafe unsafe = Unsafe.getUnsafe();

private volatile int value;

volatile关键字用来保证内存的可见性(但不能保证线程安全性),线程读的时候直接去主内存读,写操作完成的时候立即把数据刷新到主内存当中。

CAS简要

/**

* Atomically sets the value to the given updated value

* if the current value {@code ==} the expected value.

*

* @param expect the expected value

* @param update the new value

* @return {@code true} if successful. False return indicates that

* the actual value was not equal to the expected value.

*/

public final boolean compareAndSet(int expect, int update) {

return unsafe.compareAndSwapInt(this, valueOffset, expect, update);

}

从注释就可以看出:当线程写数据的时候,先对内存中要操作的数据保留一份旧值,真正写的时候,比较当前的值是否和旧值相同,如果相同,则进行写操作。如果不同,说明在此期间值已经被修改过,则重新尝试。

compareAndSet使用Unsafe调用native本地方法CAS(CompareAndSet)递增数值。

CAS利用CPU调用底层指令实现。

两种方式:总线加锁或者缓存加锁保证原子性。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

时间: 2019-06-22

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值