java线程可见性 [英] java thread visibility

查看:114
本文介绍了java线程可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我阅读实践中的java并发c03时,我对以下程序感到困惑:

When I read the "java concurrency in practice" c03, I was confused by the following program:

public class NoVisibility { 
    private static boolean ready; 
    private static int number; 

    private static class ReaderThread extends Thread { 
        public void run() { 
            while (!ready) 
                Thread.yield(); 
            System.out.println(number); 
        } 
    } 

    public static void main(String[] args) { 
        new ReaderThread().start(); 
        number = 42; 
        ready = true; 
    } 
}

由于重新排序和线程可见性,永远不会停止,或者输出可能为零,但我已经尝试过很多次,输出总是42.
所有的原因是我太幸运了吗?

Because of the reordering and thread visibility, the loop may never stop, or the output may be zero, but I have tried many times, and the output is always 42. All the reason is I'm too lucky?

推荐答案


所有原因是我太幸运了吗?

All the reason is I'm too lucky?

不一定。这将取决于你的处理器架构和JVM实现。这是微妙的记忆模型问题的问题之一:它们可能很难在野外繁殖。

Not necessarily. It will depend on your processor architecture and JVM implementation too. That's one of the problems with subtle memory model issues: they can be very hard to reproduce in the wild.

这篇关于java线程可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆