根据 Java 并发实践,如果我们想在 ThreadPoolExecutor 中添加日志记录、计时、监控功能,那么我们应该对其进行扩展。假设如果我们像下面这样扩展它:
// code taken from java concurrency in practice
public class TimingThreadPool extends ThreadPoolExecutor
{
private final ThreadLocal<Long> startTime
= new ThreadLocal<Long>();
private final Logger log = Logger.getLogger("TimingThreadPool");
private final AtomicLong numTasks = new AtomicLong();
private final AtomicLong totalTime = new AtomicLong();
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
log.fine(String.format("Thread %s: start %s", t, r));
startTime.set(System.nanoTime());
}
protected void afterExecute(Runnable r, Throwable t) {
try {
long endTime = System.nanoTime();
long taskTime = endTime - startTime.get();
numTasks.incrementAndGet();
totalTime.addAndGet(taskTime);
log.fine(String.format("Thread %s: end %s, time=%dns",
t, r, taskTime));
} finally {
super.afterExecute(r, t);
}
}
protected void terminated() {
try {
log.info(String.format("Terminated: avg time=%dns",
totalTime.get() / numTasks.get()));
} finally {
super.terminated();
}
}
}
我的疑问是你将如何使用这个类,因为如果你创建 ExecutorService,它总是返回一个 ThreadPoolExecutor 的实例。那么你将如何插入这个类来显示日志(需要客户端代码才能使用它)。
提前致谢!!!抱歉,如果我在提到问题时犯了任何错误。