-
ThreadPoolExecutor类中提供了几个hook方法
class ThreadPoolExecutor { ... protected void beforeExecute(Thread t, Runnable r) { } protected void afterExecute(Runnable r, Throwable t) { } protected void terminated() { } ... }所以这几个方法可以自己扩展
beforeExecute是在执行任务前被调用;aferExecute在执行任务后被调用(无论是否抛出异常都会执行);terminated在线程池关闭时调用
public class TimingThreadPool extends ThreadPoolExecutor { public TimingThreadPool() { super(1, 1, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); } 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(); } } }
chapter08_线程池的使用_4_扩展ThreadPoolExecutor
最新推荐文章于 2025-10-31 11:29:39 发布
本文介绍如何通过扩展ThreadPoolExecutor类中的hook方法,实现对线程执行前后及线程池关闭时的操作。具体展示了TimingThreadPool类的实现,该类记录了每个任务的执行时间和平均执行时间。
1307

被折叠的 条评论
为什么被折叠?



