天天看點

自定義線程工廠JAVA

public class MyThreadFactory implements ThreadFactory{
  private final String poolName;

  public MyThreadFactory(String poolName){
    this.poolName = poolName;
  }

  ppublic Thread newThread(Runnable runnable){
    return new MyAppThread(runnable,poolName);
  }

}

public class MyAppThread extends Thread{
  public static final String DEFAULT_NAME = "MyAppThread";
  private static volatile boolean debugLifecycle = false;
  private static final AtomicInteger created = new AtomicInteger();
  private static final AtomicInteger alive = new AtomicInteger();
  private static final Logger log = Logger.getAnonymousLogger();

  public MyAppThread(Runnable runnable){
    this(runnable,DEFAULT_NAME);
  }

  public MyAppThread(Runnable runnable,String name){
    super(runnable,name+"-"+created.incrementAndGet());
    setUncaughtExceptionHandler{
      new Thread.UncaughtException(Thread t,Throwable e){
        log.log(Level.SEVERE,"UNCAUGHT IN the");
      }
    }
  }
  

  public void run(){
    boolean dubug = debugLifcycle;
    try{
      alive.incrementAndGet();
      super.run();
    }finally{
      alive.decrementAndGet();
      if(){
         log.log();      
      }
    }
  }
}