小编Leg*_*ort的帖子

是一个易失性的布尔开关只由一个线程写入线程安全吗?

我有以下代码:

public class Simulation
{       
    public static volatile boolean  IS_EVEN_TICK;
}
Run Code Online (Sandbox Code Playgroud)

以及另一个(runnable)类中的以下内容:

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

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

变量是否足够易变,以确保所有线程从中读取正确的值,或者我是否需要同步对变量的访问?

java multithreading synchronization volatile

3
推荐指数
1
解决办法
243
查看次数

标签 统计

java ×1

multithreading ×1

synchronization ×1

volatile ×1