【发布时间】:2013-11-06 08:46:24
【问题描述】:
受question的启发,我写了测试:
public class Main {
private static final long TEST_NUMBERS = 5L;
private static final long ITERATION_NUMBER = 100000L;
private static long value;
public static void main(final String [] args) throws Throwable {
for(int i=0; i<TEST_NUMBERS; i++) {
value = 0;
final Thread incrementor = new Thread(new Incrementor());
final Thread checker = new Thread(new Checker());
incrementer.start();
checker.start();
checker.join();
incrementer.join();
}
}
static class Incrementor implements Runnable {
public void run() {
for(int i=0; i<ITERATION_NUMBER; i++){
++value;
}
}
}
static class Checker implements Runnable {
public void run() {
long nonEqualsCount = 0;
for(int i=0; i<ITERATION_NUMBER; i++){
if(value != value) {
++nonEqualsCount;
}
}
System.out.println("nonEqualsCount = " + nonEqualsCount);
}
}
}
这个程序是普通情况下打印出来的:
nonEqualsCount = 12; //or other non 0 value;
nonEqualsCount = 0;
nonEqualsCount = 0;
nonEqualsCount = 0;
nonEqualsCount = 0;
首先:我解释这种行为是存在 JIT 编译器。 “预热”后每个线程的 JIT 编译器缓存值非 volatile 字段。对吗?
第二:如果第一个正确或不正确,我该如何验证?
附: - 我知道 PrintAssebly-option。
更新:环境:Windows 7 64bit,JDK 1.7.0_40-b43(Hot Spot)。
【问题讨论】:
-
尝试使用 public void safePrintln(String s) { synchronized (System.out) { System.out.println(s); } }
-
@barn.gumbl:System.out 已同步。见 (PrintStream)[grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/…
标签: java multithreading jit non-volatile