原子操作和多线程 [英] Atomic Operations and multithreading
问题描述
最近我正在阅读一个教程,因为我遇到了一个声明,说明了..
Recently I was reading a tutorial, in that I came across a statement that says..
Java语言规范保证读取或写入变量是一个原子操作(除非变量的类型为 long
或 double
)。类型为的操作变量long
或 double
只有在使用 volatile
关键字声明时才是原子的。
"The Java language specification guarantees that reading or writing a variable is an atomic operation(unless the variable is of type long
or double
). Operations variables of type long
or double
are only atomic if they declared with the volatile
keyword."
AtomicInteger
或 AtomicLong
提供<$ c $等方法c> getAndDecrement(), getAndIncrement()
和 getAndSet()
这是原子的。
AtomicInteger
or AtomicLong
that provides methods like getAndDecrement()
, getAndIncrement()
and getAndSet()
which are atomic.
我对上述陈述感到困惑..请你澄清何时使用 AtomicInteger
或 AtomicLong
类。
I got confused a bit with the above statement.. could you please clarify when to use AtomicInteger
or AtomicLong
classes.
推荐答案
执行 a = 28
( a
是 int
)是原子操作。但是,执行 a ++
不是原子操作,因为它需要读取a的值,增量和对结果的写入。因此,如果您使用 a ++
来实现线程安全计数器,您可以让两个线程同时读取该值(例如26),然后同时增加它和同时写它,结果是27而不是28。
Doing a = 28
(with a
being an int
) is an atomic operation. But doing a++
is not an atomic operation because it requires a read of the value of a, an incrementation, and a write to a of the result. As a result, if you used a++
to implement a thread-safe counter, you could have two threads reading the value concurrently (26 for example), then have both increment it and writing it concurrently, resulting in 27 as a result, instead of 28.
AtomicInteger通过提供你列出的原子操作来解决这个问题。在我的示例中,您将使用 incrementAndGet()
,这将保证结束值为28而不是27。
AtomicInteger solves this issue by providing atomic operations like the ones you listed. In my example, you would use incrementAndGet()
for example, which would guarantee the end value is 28 and not 27.
这篇关于原子操作和多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!