简体   繁体   English

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

[英]Strange behaviour in Java concurrency using no synchronization

In Java Concurrency in Practice there is a sample that made me confused: 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");
    }
}

I can understand reordering makes the loop to never break, but I can't understand why "1", "2" and "3" are never printed to console. 我可以理解重新排序使循环永不中断,但我无法理解为什么“1”,“2”和“3”永远不会打印到控制台。 Could any body help? 身体有帮助吗?

You don't spawn a new thread but run it in the current one. 您不会生成新线程,而是在当前线程中运行它。 Use the start() method instead. 请改用start()方法。

Since you run() executes on the main thread and that method runs in an endless loop you'll never reach the System.out.println() statements (and neither do you reach ready = true; ). 由于run()在主线程上执行,并且该方法在无限循环中运行,因此您永远不会到达System.out.println()语句(并且您也没有达到ready = true; )。

From the JavaDoc on run() : 从runD run()上的JavaDoc:

If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; 如果使用单独的Runnable运行对象构造此线程,则调用该Runnable对象的run方法; otherwise, this method does nothing and returns. 否则,此方法不执行任何操作并返回。

And start() : start()

Causes this thread to begin execution; 导致此线程开始执行; the Java Virtual Machine calls the run method of this thread. Java虚拟机调用此线程的run方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM