根据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 的实例。那么您将如何插入此类来显示日志记录(需要客户端代码才能使用它)。
先谢谢了!!!抱歉,如果我在提到问题时犯了任何错误。
最佳答案
你的类缺少构造函数,没有它们就无法工作
public class TimingThreadPool extends ThreadPoolExecutor {
public TimingThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
// ...
}
此外,您可以查看 Executors
实现并在您的类中执行类似的操作
public static ExecutorService newFixedThreadPool(int nThreads) {
return new TimingThreadPool(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
关于java - 扩展后ThreadPoolExecutor的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14643482/