ThreadPoolExecutor 是可扩展的,它提供了几个可以在子类中改写的方法:beforeExecute、afterExecute、terminated。这些方法可以用于扩展ThreadPoolExecutor的行为。
在执行任务的线程中会调用beforeExecute和afterExecute等方法,在这些方法中可以添加日志、计时、监视或统计信息收集等功能。
新建一个线程池类,继承ThreadPoolExecutor,重写对应方法:
- beforeExecute:线程池中任务运行前执行。
- afterExecute:线程池中任务运行完毕后执行。
- terminated:线程池退出后执行。
通过这三个方法可以监控每个任务的开始、结束等,实列代码如下。
import java.util.concurrent.*;
public class ThreadPoolExtend extends ThreadPoolExecutor {
public ThreadPoolExtend(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
System.out.println("线程准备执行");
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
System.out.println("线程执行完毕");
}
@Override
protected void terminated() {
System.out.println("线程池退出");
}
}
注意事项:
- 无论任务是正常返回,还是抛出一个异常,afterExecute 都会被调用。如果任务在完成后带有一个 Error,那么就不会调用 afterExecute。
- 如果 beforeExecute 抛出一个 RuntimeException,那么任务将不被执行,并且 afterExecute 也不会被调用。
- 在线程完成关闭操作时调用 terminated,也就是在所有任务都已经完成并且所有工作者线程也已经关闭后。terminated 可以用来释放 Executor 在其生命周期里分配的各种资源,此外还可以执行发送通知、记录日志或者收集 finalize 统计信息等操作。