ThreadPoolExecutor之三:自定义线程池-扩展示例

本文展示了一个使用并发线程池执行多个任务并统计每个任务执行时间的示例,包括线程创建、执行、结束时间的记录及平均时间计算。

ThreadPoolExecutor是可扩展的,下面一个示例:

package com.dxz.threadpool.demo1;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class StatThreadPoolExecutor extends ThreadPoolExecutor {

    private final ThreadLocal<Long> startTime = new ThreadLocal<Long>();
    private final AtomicLong numTasks = new AtomicLong();
    private final AtomicLong totalTime = new AtomicLong();

    public StatThreadPoolExecutor(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);
        System.out.println(String.format("beforeExecute() 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);
            System.out.println(String.format("afterExecute() : end '%s', time=%dns", r, taskTime));
        } finally {
            super.afterExecute(r, t);
        }
    }

    @Override
    protected void terminated() {
        try {
            System.out.println(String.format("terminated() Terminated: avg time=%dns", totalTime.get() / numTasks.get()));
        } finally {
            super.terminated();
        }
    }
}

启动程序:

package com.dxz.threadpool.demo1;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class StatClient {
    public static void main(String[] args) {
        ThreadPoolExecutor exec = new StatThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>());
        exec.execute(new Thread(new Printer(5),"t5"));
        exec.execute(new Thread(new Printer(4),"t4"));
        exec.execute(new Thread(new Printer(3),"t3"));
        exec.execute(new Thread(new Printer(2),"t2"));
        exec.execute(new Thread(new Printer(1),"t1"));
        exec.shutdown();
    }

}

class Printer implements Runnable {
    private int sleepTime;

    public Printer(int sleepTime) {
        this.sleepTime = sleepTime;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " is running.");
        try {
            TimeUnit.SECONDS.sleep(sleepTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

结果:

beforeExecute() Thread 'Thread[pool-1-thread-5,5,main]': start 'Thread[t1,5,main]'
beforeExecute() Thread 'Thread[pool-1-thread-4,5,main]': start 'Thread[t2,5,main]'
beforeExecute() Thread 'Thread[pool-1-thread-1,5,main]': start 'Thread[t5,5,main]'
beforeExecute() Thread 'Thread[pool-1-thread-2,5,main]': start 'Thread[t4,5,main]'
beforeExecute() Thread 'Thread[pool-1-thread-3,5,main]': start 'Thread[t3,5,main]'
pool-1-thread-2 is running.
pool-1-thread-1 is running.
pool-1-thread-5 is running.
pool-1-thread-4 is running.
pool-1-thread-3 is running.
afterExecute() : end 'Thread[t1,5,main]', time=1001000273ns
afterExecute() : end 'Thread[t2,5,main]', time=2001157367ns
afterExecute() : end 'Thread[t3,5,main]', time=3000630301ns
afterExecute() : end 'Thread[t4,5,main]', time=4000804066ns
afterExecute() : end 'Thread[t5,5,main]', time=5001279195ns
terminated() Terminated: avg time=3000974240ns

 

可以看到,在测试类client中通过execute了五个线程,然后分别对这五个线程进行统计,最后统计出各个线程的耗时平均时间。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值