代码很简单。
// not annotated with volatile
public static int I = 0;
public static int test(){
I = 1;
return I;
}
有一个线程调用方法test
。
test
方法是否有可能返回值'0'?
换句话说,共享变量的读取可能不会看到同一线程的修改。
更新
这个问题很简单,但我把它弄得晦涩难懂,我真的很抱歉。
a thread
表示单个线程
。
问题与 it 重复.
最佳答案
任何没有用 java language specification 的术语解释的答案只是部分正确,如果完全正确的话。
您需要明确区分发生在单个线程中并通过 program order 绑定(bind)在一起的操作。而这又会创建一个 happens-before connection ,具体通过:
If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).
这条规则告诉你,如果你在单线程世界中考虑这段代码,它总是会打印 1
。
另一方面,创建 synchronizes with 的操作跨不同线程的连接,隐式地创建happens-before,通过:
If an action x synchronizes-with a following action y, then we also have hb(x, y).
在您的情况下,I
是一个 plain 字段,因此与其相关的每个操作都是一个 plain store 和/或一个 < em>普通负载。根据 JLS
,这样的存储和加载根本不会创建任何连接。因此,如果涉及写入线程,读取 I
的某些线程始终可以将其读取为0
。
关于java - 线程内一致性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65929942/