关于“Java并发实践"的问题例子 [英] question about "Java Concurrency in Practice" example
问题描述
我正在查看 Brian Goetz 撰写的Java 并发实践"中的代码示例.他说这段代码可能会一直处于无限循环中,因为'ready' 的值可能永远不会对阅读器线程可见".我不明白这怎么会发生...
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;
}
}
推荐答案
因为 ready
未标记为 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.
查看易失性关键字.
这篇关于关于“Java并发实践"的问题例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!