为什么对非易失性的写入对主线程可见?

问题描述 投票:0回答:1

想象以下程序。

class Main {


    static class Whatever {
        int x = 0;
    }


    public static void main(String[] args) {
        Whatever whatever = new Whatever();

        Thread t = new Thread(() -> {
            whatever.x = 1;
        });
        t.start();
        try {
            t.join();
        }
        catch (InterruptedException e) {
        }

        System.out.println(whatever.x);
    }
}

主线程已缓存whatever,并且x设置为0。另一个线程启动,缓存whatever并将缓存的x设置为1

输出为

1

因此主线程已经看到了写入。为什么会这样?

为什么对共享缓存进行写操作,为什么主线程使它的缓存无效以从共享缓存中读取?为什么我在这里不需要volatile

java multithreading java-memory-model
1个回答
2
投票

由于连接了主线程。看到JLS中的17.4.5:

一个线程中的所有动作发生-在任何其他线程成功从该线程上的join()返回之前。

© www.soinside.com 2019 - 2024. All rights reserved.