线程无法正常停止

Wei*_*ong 2 java

我是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)

And*_*ner 8

因为您尚未指示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)

不允许此优化。

  • 优化是[内存模型](https://docs.oracle.com/javase/specs/jls/se9/html/jls-17.html#jls-17.4)的结果。仅在循环中使用“ stop”是不够的:您需要做一些事情来建立变量的写和读之间的事前关系:同步就是一回事;使变量易变是另一回事。 (2认同)