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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tomorrow_fine/article/details/80503278
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"));
        }
    }
}

猜你喜欢

转载自blog.csdn.net/tomorrow_fine/article/details/80503278
今日推荐