Java自定义线程池-记录每个线程执行耗时
ThreadPoolExecutor是可扩展的,其提供了几个可在子类化中改写的方法,如下:
protected void beforeExecute(Thread t, Runnable r) { }
protected void afterExecute(Runnable r, Throwable t) { }
protected void terminated() { }
现基于此,完成一个统计每个线程执行耗时,并计算平均耗时的 自定义线程池样例。通过 beforeExecute、afterExecute、terminated 方法来添加日志记录和统计信息收集。为了测量任务的运行时间,beforeExecute必须记录开始时间并把它保存到一个ThreadLocal变量中,然后由afterExecute来读取。同时,使用两个 AtomicLong变量,分别用以记录已处理的任务数和总的处理时间,并通过terminated来输出包含平均任务时间的日志消息。
自定义线程池代码如下:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger; /**
* 自定义线程池
*/
public class TimingThreadPool extends ThreadPoolExecutor { private final ThreadLocal<Long> startTime = new ThreadLocal<>();
private final Logger log = Logger.getLogger("TimingThreadPool");
private final AtomicLong numTasks = new AtomicLong();
private final AtomicLong totalTime = new AtomicLong(); public TimingThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
} @Override
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
log.info(String.format("Thread %s: start %s",t,r));
startTime.set(System.nanoTime());
} @Override
protected void afterExecute(Runnable r, Throwable t) {
try {
long endTime = System.nanoTime();
long taskTime = endTime - startTime.get();
numTasks.incrementAndGet();
totalTime.addAndGet(taskTime);
log.info(String.format("Thread %s: end %s, time=%dns",t,r,taskTime)); } finally {
super.afterExecute(r,t);
}
} @Override
protected void terminated() {
try {
log.info(String.format("Terminated: avg time=%dns",totalTime.get() / numTasks.get()));
} finally {
super.terminated();
}
}
}
测试执行效果代码如下:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit; /**
* 测试自定义线程池
*/
public class TestCustomThreadPool { public static void main(String[] args) { try {
TimingThreadPool threadPool = new TimingThreadPool(,,0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()); List<TestCallable> tasks = new ArrayList<>(); for (int i = ; i < ; i++) {
tasks.add(new TestCallable());
} List<Future<Long>> futures = threadPool.invokeAll(tasks);
for (Future<Long> future :
futures) {
System.out.print(" - "+future.get());
}
threadPool.shutdown(); } catch (Exception e) {
e.printStackTrace();
} } static class TestCallable implements Callable<java.lang.Long> { @Override
public Long call() throws Exception {
long total = ;
for (int i = ; i < ; i++) {
long now = getRandom();
total += now;
}
Thread.sleep(total);
return total;
} public long getRandom () {
return Math.round(Math.random() * );
}
} }
执行结果:

Java自定义线程池-记录每个线程执行耗时的更多相关文章
- Java如何判断线程池所有任务是否执行完毕
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Tes ...
- Java 线程池记录
Java通过Executors提供四种线程池,分别为:newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程.newFixe ...
- Java多线程系列--“JUC线程池”03之 线程池原理(二)
概要 在前面一章"Java多线程系列--“JUC线程池”02之 线程池原理(一)"中介绍了线程池的数据结构,本章会通过分析线程池的源码,对线程池进行说明.内容包括:线程池示例参考代 ...
- Java多线程系列--“JUC线程池”04之 线程池原理(三)
转载请注明出处:http://www.cnblogs.com/skywang12345/p/3509960.html 本章介绍线程池的生命周期.在"Java多线程系列--“基础篇”01之 基 ...
- Java线程池二:线程池原理
最近精读Netty源码,读到NioEventLoop部分的时候,发现对Java线程&线程池有些概念还有困惑, 所以深入总结一下 Java线程池一:线程基础 为什么需要使用线程池 Java线程映 ...
- Java多线程系列--“JUC线程池”01之 线程池架构
概要 前面分别介绍了"Java多线程基础"."JUC原子类"和"JUC锁".本章介绍JUC的最后一部分的内容——线程池.内容包括:线程池架构 ...
- Java多线程系列--“JUC线程池”02之 线程池原理(一)
概要 在上一章"Java多线程系列--“JUC线程池”01之 线程池架构"中,我们了解了线程池的架构.线程池的实现类是ThreadPoolExecutor类.本章,我们通过分析Th ...
- Java多线程系列--“JUC线程池”05之 线程池原理(四)
概要 本章介绍线程池的拒绝策略.内容包括:拒绝策略介绍拒绝策略对比和示例 转载请注明出处:http://www.cnblogs.com/skywang12345/p/3512947.html 拒绝策略 ...
- 深入浅出 Java Concurrency (34): 线程池 part 7 线程池的实现及原理 (2)[转]
线程池任务执行流程 我们从一个API开始接触Executor是如何处理任务队列的. java.util.concurrent.Executor.execute(Runnable) Executes t ...
随机推荐
- VC++全屏
Win32类型的全屏代码: 1. 去掉menu ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = s ...
- 五、xadmin自定义插件2
以导入插件为例说明: 1.在xadmin-->plugins下面新建excel.py文件 2.新建ListExcelImportPlugin类,继承BaseAdminPlugin from xa ...
- 十三、MUI的日期起始和结束日期设置
MUI的日期选择器的使用 // 日期选择器 //生日选择器(不会超过今年) function fdPicker1(id) { var year=new Date().getFullYear(); va ...
- H5 55-行高
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- H5 颜色属性
07-颜色属性 我是段落 <!DOCTYPE html> <html lang="en"> <head> <meta charset=&q ...
- Python入门-Hello Word
1.python语言介绍 Python创始人:Guido Van Rossum 2.python是一种解释型.动态类型计算机程序设计语言. 解释型:程序无需编译成二进制代码,而是在执行时对语句一条一条 ...
- 记一个JS树结构路径查找
var a=[ { "id" : "0000", "text" : "R1", "children" ...
- redis 运维手册
redis cli命令 - milkty - 博客园https://www.cnblogs.com/kongzhongqijing/p/6867960.html Redis多个数据库 - EasonJ ...
- Spring.profile配合Jenkins发布War包,实现开发、测试和生产环境的按需切换
前两篇不错 Spring.profile实现开发.测试和生产环境的配置和切换 - Strugglion - 博客园https://www.cnblogs.com/strugglion/p/709102 ...
- Composer之搭建自己的包工具
作为一个标准的PHPer,必须学会优雅的使用composer,最近,萌生了一个想法,我们每搭建一个项目,里面都会有许多的公用的方法和类库,每次使用的时候就是将其拷贝过来,或者重新写一遍,过于繁琐,效率 ...