2

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

提前致谢!!!抱歉,如果我在提到问题时犯了任何错误。

4

1 回答 1

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>());
}
于 2013-02-01T10:02:17.050 回答