首页 > 解决方案 > Java 多线程和 Thread.sleep

问题描述

我在我的研究生项目中遇到了一个关于 java 多线程的问题。有两个线程。线程 A 将执行一个无限循环。在循环中,如果变量simulationSwitch为真,线程A 会做一些事情。布尔变量simualtionSwitch最初设置为 false,因此线程 A 将忙于等待,直到simualtionSwitch设置为 true。

线程 B 处理 http 请求,并在接收到 http 请求时将 SimulationSwitch 设置为 true。

让我困惑的问题来了。线程 A 不会检测到SimulationSwitch的变化并完成它的工作。但是,如果线程 A 在其循环中调用 Thread.sleep() ,那么如果线程 B 将SimulationSwitch设置为 true ,它就可以正常工作。我真的很困惑,想找出原因。

public static boolean simulationSwitch = false;

// Thread A
public void startSimulation() throws Exception {
    while(true) {
        Thread.sleep(1000); // without calling Thread.sleep(), thread A won't do anything even if simualtionSwitch is set to true
        while (simulationSwitch) {
            // do something 
        }
    }
}

// this function will be called when receiving a specific http request
public void switchOn(){
    simulationSwitch = true;
}

标签: javamultithreadingsleep

解决方案


为确保跨线程的更改可见,simulationSwitch应声明为volatile.

如果没有 volatile,那么在某些情况下更改仍然是可见的,但您不能依赖它。


推荐阅读