关于“Java并发在实践中”的问题例 [英] question about "Java Concurrency in Practice" example

查看:114
本文介绍了关于“Java并发在实践中”的问题例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看一个来自Java Concurrency in Practice的代码示例,由Brian Goetz。他说这个代码可能会停留在一个无限循环中,因为ready的值可能永远不会被reader线程看到。我不明白这怎么可能发生...

I'm looking at a code sample from "Java Concurrency in Practice" by Brian Goetz. He says that it is possible that this code will stay in an infinite loop because "the value of 'ready' might never become visible to the reader thread". I don't understand how this can happen...

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


推荐答案

准备未标记为 volatile ,并且该值可以缓存在 while 循环,因为它在 while 循环中没有更改。

Because ready isn't marked as volatile and the value may be cached at the start of the while loop because it isn't changed within the while loop. It's one of the ways the jitter optimizes the code.

因此,线程可能在 ready = true之前启动并且读取 ready = false 缓存线程本地并且从不再读取。

So it's possible that the thread starts before ready = true and reads ready = false caches that thread-locally and never reads it again.

查看 volatile关键字

这篇关于关于“Java并发在实践中”的问题例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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