java Java中的AtomicLong是做什么用的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35546956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:15:29  来源:igfitidea点击:

What is AtomicLong in Java used for?

javaatomic-long

提问by Nilotpal

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

有人可以解释一下 AtomicLong 的用途吗?例如,下面的语句有什么区别?

private Long transactionId;
private AtomicLong transactionId;

回答by Makoto

There are significantdifferences 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 Longobject when:

在以下情况下使用基本Long对象:

  • You need the wrapper class
  • You are working with a collection
  • You only want to deal with objects and not primitives (which kinda works out)
  • 你需要包装类
  • 你正在处理一个集合
  • 你只想处理对象而不是基元(这有点可行)

You use an AtomicLongwhen:

您使用AtomicLong时:

  • You have to guarantee that the value can be used in a concurrent environment
  • You don't need the wrapper class (as this class will not autobox)
  • 必须保证该值可以在并发环境中使用
  • 您不需要包装类(因为此类不会自动装箱)

Longby 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.

Long本身不允许线程互操作性,因为两个线程都可以看到和更新相同的值,但是使用AtomicLong,围绕多个线程将看到的值有相当不错的保证。

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

实际上,除非您曾经费心使用线程,否则您不需要使用AtomicLong.