我是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);
}
}
Run Code Online (Sandbox Code Playgroud)
我也尝试运行以下代码,它可能会停止。谁能告诉我为什么?谢谢
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);
}
}
Run Code Online (Sandbox Code Playgroud)
因为您尚未指示stop可能会被多个线程更改和读取的编译器,所以:
private static boolean stop;
Run Code Online (Sandbox Code Playgroud)
可以对此进行优化:
while (!stop) {
}
Run Code Online (Sandbox Code Playgroud)
至
if (!stop) {
while (true) {
}
}
Run Code Online (Sandbox Code Playgroud)
如果stop最初为假,它将永远不会停止。
宣告stop volatile:
private static volatile boolean stop;
Run Code Online (Sandbox Code Playgroud)
不允许此优化。