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

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");
    }
}

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

解决方法:

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

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

从runD()上的JavaDoc:

If this thread was constructed using a separate Runnable run object, then that Runnable object’s run method is called; otherwise, this method does nothing and returns.

并开始():

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

上一篇:javascript – 如何使表单提交同步?


下一篇:java – 释放“同步”锁