我是 Java 并发编码新手,遇到了一个问题。以下代码在运行时无法停止。谁能告诉我为什么?谢谢
import java.util.concurrent.TimeUnit;
public class Test {
private static boolean stop;
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
System.out.println(Thread.currentThread());
System.out.println(stop);
while (!stop) {
}
}).start();
TimeUnit.SECONDS.sleep(1);
stop = true;
System.out.println(Thread.currentThread());
System.out.println(stop);
}
}
我还尝试运行以下代码,它可以停止。谁能告诉我为什么?谢谢
import java.util.concurrent.TimeUnit;
public class Test {
private static boolean stop;
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
System.out.println(Thread.currentThread());
System.out.println(stop);
while (!stop) {
System.out.println(" ");
}
}).start();
TimeUnit.SECONDS.sleep(1);
stop = true;
System.out.println(Thread.currentThread());
System.out.println(stop);
}
}
最佳答案
因为您没有向编译器表明 stop
可能会被多个线程更改和读取:
private static boolean stop;
允许优化:
while (!stop) {
}
至
if (!stop) {
while (true) {
}
}
如果 stop
最初为 false,则永远不会停止。
声明停止
volatile
:
private static volatile boolean stop;
不允许此优化。
关于java - 线程未正确停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55414370/