Java中的奇怪行为,在多线程程序中使用非同步访问

Hei*_*Ody 5 java concurrency

我更改了一个值,用于确定while循环何时在单独的线程中终止.
我不想知道如何使这个工作.如果我只通过synchronized getters/setters访问变量测试,它按预期工作.

我原以为,如果一些读/写命令由于并发而丢失,程序有时不会终止,但它永远不会.这让我感到困惑..
我想知道为什么程序永远不会终止,没有print-command.我想了解为什么print-command会改变任何东西..

     

    public class CustomComboBoxDemo  {
        public static boolean test = true;
        public static void main(String[] args) {
            Thread user =new Thread(){
                @Override
                public void run(){
                    try {
                        sleep(2000);
                    } catch (InterruptedException e) {}
                    test=false;
                }
            };
            user.start();
            while(test) {
                System.out.println("foo"); //Without this line the program does not terminate..
            }
        }
    }

Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 8

最可能的解释是变量只读一次,变成while无限循环(或无操作).由于您尚未声明testvolatile,因此允许编译器执行此类优化.

一旦从循环内调用外部函数,编译器就不能再证明test在循环迭代中保持不变,并且不执行优化.