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;
)。
来自 run()
上的 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.
和start()
:
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
关于java - 不使用同步的 Java 并发中的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8956464/