gpt4 book ai didi

java - 仅由一个线程写入的 volatile boolean 开关是线程安全的吗?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:47:55 24 4
gpt4 key购买 nike

我有以下代码:

public class Simulation
{
public static volatile boolean IS_EVEN_TICK;
}

以及另一个(可运行)类中的以下内容:

public void run()
{
while (true)
{
// flip the "even/uneven tick" switch
Simulation.IS_EVEN_TICK = !Simulation.IS_EVEN_TICK;
}
}

据我所知,这通常不是线程安全的,因为写入 Simulation.IS_EVEN_TICK 取决于该变量的当前值。然而,这个线程是唯一一个曾经写入变量的线程,所有其他线程只会读取变量(如果它们访问它的话)。

变量的易变性是否足以确保所有线程都从中读取正确的值,还是我仍然需要同步对变量的访问?

最佳答案

However this thread is the only thread that ever writes to the variable... Is the variable being volatile enough to make sure that all threads read the right value from it.

如果只有一个作者,那么就没有竞争条件。您不需要跨变量同步。

您可能会考虑使用 AtomicBoolean,但它不支持 toggle() 方法,因此如果您有多个编写器切换值,则必须执行类似以下内容:

private final AtomicBoolean isEvenTick = new AtomicBoolean();
...
boolean currentValue;
do {
currentValue = isEvenTick.get();
} while (!isEvenTick.compareAndSet(currentValue, !currentValue);

关于java - 仅由一个线程写入的 volatile boolean 开关是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19543725/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com