线程池执行线程任务花费的时间

public class CounterPoolExecutor extends ThreadPoolExecutor { 
    private AtomicInteger count = new AtomicInteger(0);//统计执行次数
    private long startTime = System.currentTimeMillis();
    private String funcname = "";
    private final static int COUNT = 100;

    public CounterPoolExecutor(int corePoolSize, int maximumPoolSize,
                               long keepAliveTime, TimeUnit unit,
                               BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
  //线程执行结束时
        int l = count.addAndGet(1);
        if (l == COUNT) {
            System.out.println(funcname + "spend time:" + (System.currentTimeMillis() - startTime));
        }
    }

    public static void main(String[] args) {
        ExecutorService executorService = new CounterPoolExecutor(50, 100, 60L, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>());
        for (int i = 0; i < 100; i++) {
            executorService.execute(() -> System.out.print("1"));
        }
    }
}
    原文作者:无名同学
    原文地址: https://blog.csdn.net/tomorrow_fine/article/details/80503278
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞