这个问题已经在两篇博文(http://dow.ngra.de/2008/10/27/when-systemcurrenttimemillis-is-too-slow/,http://dow.ngra.de/2008/10 /28/what-do-we-really-know-about-non-blocking-concurrency-in-java/),但我还没有听到明确的答案。如果我们有一个线程这样做:
public class HeartBeatThread extends Thread {
public static int counter = 0;
public static volatile int cacheFlush = 0;
public HeartBeatThread() {
setDaemon(true);
}
static {
new HeartBeatThread().start();
}
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
counter++;
cacheFlush++;
}
}
}
以及许多运行以下命令的客户端:
if (counter == HeartBeatThread.counter) return;
counter = HeartBeatThread.cacheFlush;
它是线程安全的吗?