在Java concurrency in practice一书中,有一个自定义线程的例子(见 8.3.4 节的清单 8.7)。我粘贴了下面的代码。有一件事我不太明白。也就是说,该run()
方法在使用 volatile 变量debugLifecycle
之前对其进行复制。它有一个注释复制调试标志,以确保始终一致的值。是否需要在此处复制变量?如果是,为什么?
public class MyAppThread extends Thread {
public static final String DEFAULT_NAME = "MyAppThread";
private static volatile boolean debugLifecycle = false;
public MyAppThread(Runnable r) {
this(r, DEFAULT_NAME);
}
public MyAppThread(Runnable runnable, String name) {
super(runnable, name + "-" + created.incrementAndGet());
setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t,
Throwable e) {
log.log(Level.SEVERE,
"UNCAUGHT in thread " + t.getName(), e);
}
});
}
public void run() {
// Question: why copy the volatile variable here?
// Copy debug flag to ensure consistent value throughout.
boolean debug = debugLifecycle;
if (debug) log.log(Level.FINE, "Created " + getName());
try {
alive.incrementAndGet();
super.run();
} finally {
alive.decrementAndGet();
if (debug) log.log(Level.FINE, "Exiting " + getName());
}
}
}