Java 中的原子性是什么

What is Atomicity in Java

我正在研究 JAVA 并发实践,发现原子操作的定义如下:

Operation A, B are atomic with respect to each other if from the perspective of thread executing A, when another thread executes B, either all of B has executed or none of it has. An atomic operation is one that is atomic with respect to all operation, including itself, that operates on the same data.

假设我有两个线程 A 和 B 都在访问 AtomicLong 变量计数。
假设线程 A 读取计数,线程 B 正忙于执行 count.incrementAndGe() 操作。
在这种情况下,根据上述定义(所有 B 都已执行或 none 已执行):

A) ThreadA查看count之前的值(因为count还没更新)

B) ThreadA 会等到 ThreadB 完成操作,然后看到最新的值。

根据我的理解,它应该是 B,否则我们仍然会出现竞争条件。

您描述的情况称为“数据竞争”。线程 A 将赢得比赛(它看到初始值),或者线程 B 将赢得比赛(线程 A 看到最终值。)除非您提供了一些明确的方法来强制线程以特定顺序访问变量, 那么就无法知道谁会赢得比赛。


“原子性”意味着线程B要么看到原子操作前的数据,要么在操作完成后看到。线程 B 永远看不到它处于 half-way-done 状态。

用于更新单个 64 位 long 值。如果 64 位值在 32 位硬件上 torn,那么它几乎可以是“half-way-done”的唯一方式。如果包含 64 位值的两个 32 位字中的一个已更新,而另一个没有更新,它将被“撕裂”。