扩展后使用ThreadPoolExecutor

时间:2013-02-01 09:47:10

标签: java concurrency

根据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的实例。那么你将如何插入这个类来显示记录(需要客户端代码来使用它)。

提前致谢!!!对不起,如果我在提到这个问题时犯了错误。

1 个答案:

答案 0 :(得分:4)

你的类缺少构造函数,没有它们就无法工作

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>());
}