简体   繁体   English

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);
    }
}

Hello, 你好,

Is T::do guaranteed to see always sx == 101? T::do保证总能看到sx == 101吗? Why it is or why it is not? 它为什么或为什么不是?

Thanks in advance for your help. 在此先感谢您的帮助。

When you start a thread, this introduces a memory barrier where anything which happened before you started the thread will be visible. 当你启动一个线程时,这会引入一个内存屏障,在你可以看到启动线程之前发生的任何事情。 Note: starting a thread takes a very long time in computer terms. 注意:在计算机术语中启动一个线程需要很长时间。

BTW System.out.println is a synchronized method which add full read/write memory barriers although in this case, that won't matter/ BTW System.out.println是一个同步方法,它增加了完整的读/写内存障碍,尽管在这种情况下,这无关紧要/

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

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