Java 线程中的内存顺序和可见性

Memory order and visibility in Java thread

class S {
    public int x = 100; 
}

class T {
    public void do(S s){
       new Thread( () -> { 
            System.out.println(s.x);
        };).start();
    }
}


class M {
    public static void main(String[] args){
       T t = new T();
       S s = new S();
       s.x = 101;
       t.do(s);
    }
}

您好,

是否T::do保证总是看到s.x == 101?为什么是或不是?

在此先感谢您的帮助。

当您启动一个线程时,这会引入一个内存屏障,在您启动该线程之前发生的任何事情都将是可见的。注意:启动一个线程在计算机方面需要很长时间。

顺便说一句 System.out.println 是一种同步方法,它添加了完整的 read/write 内存屏障,尽管在这种情况下,这无关紧要/