我想自己尝试Java lang 规范示例,但显然有些东西我不明白。我的理解是 volatile 计数器的递增顺序应该与代码中显示的顺序相同。“令人惊讶的是”我得到一个随机计数器值,因为一个计数器有时小于、等于和大于另一个。有没有人可以解释我错过了什么?
下面的代码和输出:
public class C {
private static volatile int i = 0;
private static volatile int j = 0;
static void one() {
i++;
j++;
}
static void two() {
int a = i;
int b = j;
if(a < b)
System.out.println(a + " < " + b);
if(a > b)
System.out.println(a + " > " + b);
if(a == b)
System.out.println(a + " = " + b);
}
public static void main(String[] args) throws Exception {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
while(true)
one();
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
while(true)
two();
}
});
t1.start();
t2.start();
Thread.sleep(5000);
System.exit(0);
}
}
输出
214559700 > 214559699
214559807 > 214559806
214559917 > 214559916
214560019 = 214560019
214560137 > 214560136
214560247 = 214560247
214560349 > 214560348
214560455 = 214560455
214560561 > 214560560
214560670 = 214560670
214560776 = 214560776
214560886 > 214560885
214560995 = 214560995
214561097 < 214561098