atomic原子类怎么在Java中使用

这期内容当中小编将会给大家带来有关atomic原子类怎么在Java 中使用,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

目前成都创新互联已为1000多家的企业提供了网站建设、域名、雅安服务器托管网站运营、企业网站设计、连云网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。

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调用底层指令实现。

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

上述就是小编为大家分享的atomic原子类怎么在Java 中使用了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注创新互联行业资讯频道。

分享文章:atomic原子类怎么在Java中使用
网站URL:https://www.cdcxhl.com/article34/iijhse.html

成都网站建设公司_创新互联,为您提供定制网站做网站商城网站微信小程序App开发

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都网站建设公司