java - 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;
}
解决方案
为确保跨线程的更改可见,simulationSwitch
应声明为volatile
.
如果没有 volatile,那么在某些情况下更改仍然是可见的,但您不能依赖它。
推荐阅读
- powershell - 按字母顺序排序,小写在大写之前?
- javascript - 音频播放并在按钮单击时停止
- c# - C# 控制台应用程序作为 Windows 窗体
- java - 当前平台不支持 ICON_IMAGE 功能
- c# - c# Json.net 不可变类
- java - 如何使用 cucumber 和 selenium 在一个 java 类中定义所有步骤定义?
- python-3.x - 使用 pygame 在 Python 中编程
- java - 使用 IOException 编写类后无法创建 JAXBContext
- php - 如何在codeigniter中选择最大数据
- vba - 从多个工作簿复制具有不同列和工作表名称的数据 - VBA