chapter08_线程池的使用_4_扩展ThreadPoolExecutor

  • ThreadPoolExecutor类中提供了几个hook方法

      class ThreadPoolExecutor {
    
          ...
    
          protected void beforeExecute(Thread t, Runnable r) { }
    
          protected void afterExecute(Runnable r, Throwable t) { }
    
          protected void terminated() { }
    
          ...
      }
    

    所以这几个方法可以自己扩展

    beforeExecute是在执行任务前被调用;aferExecute在执行任务后被调用(无论是否抛出异常都会执行);terminated在线程池关闭时调用

      public class TimingThreadPool extends ThreadPoolExecutor {
    
          public TimingThreadPool() {
    
              super(1, 1, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
          }
    
          private final ThreadLocal<Long> startTime = new ThreadLocal<Long>();
          private final Logger log = Logger.getLogger("TimingThreadPool");
          private final AtomicLong numTasks = new AtomicLong();
          private final AtomicLong totalTime = new AtomicLong();
    
          protected void beforeExecute(Thread t, Runnable r) {
    
              super.beforeExecute(t, r);
              log.fine(String.format("Thread %s: start %s", t, r));
              startTime.set(System.nanoTime());
          }
    
          protected void afterExecute(Runnable r, Throwable t) {
    
              try {
                  long endTime = System.nanoTime();
                  long taskTime = endTime - startTime.get();
                  numTasks.incrementAndGet();
                  totalTime.addAndGet(taskTime);
                  log.fine(String.format("Thread %s: end %s, time=%dns", t, r, taskTime));
              } finally {
                  super.afterExecute(r, t);
              }
          }
    
          protected void terminated() {
    
              try {
                  log.info(String.format("Terminated: avg time=%dns", totalTime.get() / numTasks.get()));
              } finally {
                  super.terminated();
              }
          }
      }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值