增加日志和计时功能的线程池

public class TimingThreadPool extends ThreadPoolExecutor{
    
    
  private final ThreadLocal<Long> startTime = new ThreadLocal<>();
  private final Logger log = Logger.getLogger("TimingThreadPool");
  private final AtomicLong numTasks = new AtomicLo ng();
  private final AtomicLong totalTime = new AtomicLong();

  protected void beforeExecute(){
    
    
    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();
      numTasks.incrementAndGet();
      totalTime.addAndGet();
      log.fine(String.format("Thread %s: end 5s",t,r,taskTime));
    }finally{
    
    
      super.afterExecute(r,t);
    }
  }

  protected void terminated(){
    
    
    try{
    
    
      log,info(String.format("Terminated: avg time=%nds",totalTime.get()/numTasks.get()));
    }finally{
    
    
      super.terminated();
    }
  }

}

猜你喜欢

转载自blog.csdn.net/weixin_37632716/article/details/118861100