Java atomic原子类的使用方法是什么

发布时间:2021-11-19 16:38:45 作者:iii
来源:亿速云 阅读:97

这篇文章主要介绍“Java atomic原子类的使用方法是什么”,在日常操作中,相信很多人在Java atomic原子类的使用方法是什么问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Java atomic原子类的使用方法是什么”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

在讲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;}@Overridepublic void run() {atomicInteger.addAndGet(1);atomicInteger.addAndGet(2);atomicInteger.addAndGet(3);atomicInteger.addAndGet(4);}}

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

打开AtomicInteger的源码可以看到:

// setup to use Unsafe.compareAndSwapInt for updatesprivate 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调用底层指令实现。

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

到此,关于“Java atomic原子类的使用方法是什么”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. atomic原子类怎么在Java 中使用
  2. Java多线程Atomic包操作原子变量与原子类的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java atomic

上一篇:如何进行Terminate Instance操作

下一篇:java虚拟机知识有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》