以下是 Brian Goetz 的Java Concurrency in Practice清单 7.20 中的代码:
public class CheckForMail {
public boolean checkMail(Set<String> hosts, long timeout, TimeUnit unit)
throws InterruptedException {
ExecutorService exec = Executors.newCachedThreadPool();
final AtomicBoolean hasNewMail = new AtomicBoolean(false);
try {
for (final String host : hosts)
exec.execute(new Runnable() {
public void run() {
if (checkMail(host)) hasNewMail.set(true);
}
});
} finally {
exec.shutdown();
exec.awaitTermination(timeout, unit);
}
return hasNewMail.get();
}
private boolean checkMail(String host) { // Check for mail return
false;
}
}
参考这段代码,Goetz 说“使用 AtomicBoolean 而不是 volatile 布尔值的原因是,为了从内部 Runnable 访问 hasMail 标志,它必须是最终的,这将排除修改它”(第 158 页) )。
为什么它必须是最终的?你不能把它变成一个非最终的布尔变量吗?