没有使用volatile,为什么循环会停止呢



package com.aoptest.test;

public class ProblemDemo {
    /*volatile*/ boolean flag = true;

    void test() {
        System.out.println("start");
        while (flag) {
            System.out.println(".");
        }
        System.out.println("end");
    }

    public static void main(String[] args) {
        ProblemDemo problemDemo = new ProblemDemo();
        new Thread(problemDemo::test).start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        problemDemo.flag = false;
    }
}

另外去掉while的循环体“System.out.println(".");”,结果很费解,sout为什么会影响结果呢

正常情况下,main程序会在1秒后结束,跟使用volatile无关。一般情况下1秒之内你的IDE会崩。请去掉循环中的输出语句