Java中的AtomicLong用于什么? [英] What is AtomicLong in Java used for?

查看:804
本文介绍了Java中的AtomicLong用于什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下AtomicLong的用途吗?例如,以下陈述的区别是什么?

Can some one explain what AtomicLong is used for? For example, what's the difference in the below statements?

private Long transactionId;
private AtomicLong transactionId;


推荐答案

显着 这两个对象之间的差异,虽然最终结果是相同的,但它们肯定是非常不同的,并且在非常不同的情况下使用。

There are significant differences between these two objects, although the net result is the same, they are definitely very different and used under very different circumstances.

你使用的是基本的对象时间:

You use a basic Long object when:


  • 你需要包装类

  • 你正在使用一个集合

  • 你只想处理对象而不是原语(有点可行)

您使用 AtomicLong 时:


  • 您必须保证该值可以在并发环境中使用

  • 您不需要包装类(因为此类不会自动装箱)

本身不允许线程互操作,因为两个线程都可以看到和更新相同的线程值,但是 AtomicLong ,有p retty体面保证多线程将看到的值。

Long by itself doesn't allow for thread interopability since two threads could both see and update the same value, but with an AtomicLong, there are pretty decent guarantees around the value that multiple threads will see.

实际上,除非你曾经打扰线程,否则你不需要使用 AtomicLong

Effectively, unless you ever bother working with threads, you won't need to use AtomicLong.

这篇关于Java中的AtomicLong用于什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆