Java并发中使用无同步的奇怪行为

Ami*_*deh 4 java concurrency synchronization

Java Concurrency in Practice中有一个让我困惑的样本:

public class Novisibility {
    private static boolean ready;
    private static int number;

    private static class ReaderThread implements Runnable {

        public void run() {
            while (!ready) {
                Thread.yield();
            }
            System.out.println(number);
        }
    }

    public static void main(String[] args) {
        System.out.println("0");
        new Thread(new ReaderThread()).run();
        System.out.println("1");
        number = 42;
        System.out.println("2");
        ready = true;
        System.out.println("3");
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以理解重新排序使循环永不中断,但我无法理解为什么"1","2"和"3"永远不会打印到控制台.身体有帮助吗?

Tho*_*mas 7

您不会生成新线程,而是在当前线程中运行它.请改用该start()方法.

由于您run()在主线程上执行并且该方法在无限循环中运行,因此您将永远不会到达System.out.println()语句(并且您也无法到达ready = true;).

来自JavaDoc run():

如果使用单独的Runnable运行对象构造此线程,则调用该Runnable对象的run方法; 否则,此方法不执行任何操作并返回.

而且start():

导致此线程开始执行; Java虚拟机调用此线程的run方法.