java - 不使用同步的 Java 并发中的奇怪行为

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

我能理解重新排序使循环永不中断,但我不明白为什么“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/

相关文章:

java - 一步一步...使用 NFC 读取标签

python - 如何按时间顺序使用multiprocessing?

java - 等待 SwingWorker 完成

Arduino UNOv3同步GPS和IMU MPU6050

java - 如何获取netflow数据包的流记录详细信息

java - SLF4J 自定义绑定(bind)不起作用

java - 在启动前确定最佳 Java 运行时参数?

java - Cassandra 连接 - 共享 'Cluster' 实例或多个?

Java将对象锁定在一个类中

java - 放入 session 中并具有动态 getter 的对象是否应该是线程安全的