在以下场景中, boolean 值“done”被设置为 true,这应该结束程序。相反,即使 while(!done) 不再是有效场景,程序也会继续运行,因此它应该停止。现在,如果我要添加线程 sleep ,即使 sleep 时间为零,程序也会按预期终止。这是为什么?
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 关键字,除非它是绝对必须的,并且我确实明白,通过将我的值暴露给所有线程(这不是我打算公开的)可以工作。
最佳答案
每个线程都为性能创建了不同的缓存版本done,您的计数器线程太忙于计算count,以至于没有机会重新加载< em>完成。
volatile 确保任何读/写都在主内存上完成,始终更新CPU缓存副本。
Thread.sleep 总是暂停当前线程,因此即使 0 你的计数器线程被中断一段时间 <1ms,这也足以让线程建议完成/em> 变量改变。
关于java - 循环完成后程序未终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58635112/