如果我对此做坏事,我很抱歉,但我有一个问题是这个问题的衍生问题:
为什么 java 5+ 中的 volatile 不会将缓存的变量副本与主内存同步?
基本上,我想看看当从变量volatile
中消除时会发生什么。a
这是原始问题的代码,应用了我的修改:
public class Test {
//volatile static private int a;
static private int a;
static private int b;
public static void main(String [] args) throws Exception {
for (int i = 0; i < 100; i++) {
new Thread() {
@Override
public void run() {
int tt = b; // makes the jvm cache the value of b
while (a==0) {
}
//some threads never get here (past the a==0 loop)
if (b == 0) {
System.out.println("error");
}
}
}.start();
}
b = 1;
a = 1;
}
}
在我的笔记本电脑(Win 7 64,JVM build 1.7.0_04-b22)上发生的事情是,没有volatile
,代码似乎永远运行(运行 20 分钟)。添加更多控制台输出告诉我,虽然 100 个线程中的大多数最终确实看到了a
from 0
to的变化1
,但总是有一些(少于 10 个)继续a==0
循环。
我的问题是:这些线程最终也会看到这种变化吗?如果是的话,与大多数类似线程相比,花费数万倍的时间来完成它是否正常?怎么来的?