【发布时间】:2020-02-26 07:51:19
【问题描述】:
在以下场景中,布尔值“完成”设置为 true,这应该结束程序。相反,即使 while(!done) 不再是有效的场景,程序也会继续运行,因此它应该停止。现在,如果我要添加一个线程睡眠,即使睡眠时间为零,程序也会按预期终止。这是为什么?
public class Sample {
private static boolean done;
public static void main(String[] args) throws InterruptedException {
done = false;
new Thread(() -> {
System.out.println("Running...");
int count = 0;
while (!done) {
count++;
try {
Thread.sleep(0); // program only ends if I add this line.
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Thread.sleep(2000);
done = true; // this is set to true after 2 seconds so program should end.
System.out.println("Done!"); // this gets printed after 2 seconds
}
}
编辑:我想了解为什么上面需要 Thread.sleep(0) 来终止。我不想使用 volatile 关键字,除非它是绝对必须的,而且我知道通过将我的值暴露给我不打算暴露的所有线程来工作。
【问题讨论】:
-
试试
private static volatile boolean done; -
这能回答你的问题吗? What is the volatile keyword useful for
-
回答您的编辑的方式:似乎对
Thread.sleep的调用会导致您的done标志的可见性更新,但这似乎是 JVM 实现特定的“功能”你真的不应该依赖。每当您想查看另一个线程写入变量的最新值时,您应该使用volatile关键字
标签: java