java-线程工厂

1、线程池需要创建一个线程,都要通过一个线程工厂来完成。默认的线程工厂创建一个新的、非后台的线程并没有特殊的配置。ThreadFactory只有唯一的方法:newThread,它会在线程池需要创建一个新线程时调用。

2、利用安全策略为某些特定的代码基授予权限,可能想要使用Executors中的privilegedThreadFactory工厂来构建你的线程工厂。不使用privilegedThreadFactor的话,这样创建出来的线程池的线程所继承的权限,是客户调用execute或submit的当时,一个线程所需要的权限。

3、很可能需要使用定制的线程工厂。它可能希望为池线程指明一个UncaughtExceptionHandler,或实例化一个定制的THread类实例。

public class MyThreaadFactory implements ThreadFactory{

    privatefinal String poolName;

   

   public  MyThreadFactory(String poolName){

       this.poolName=poolName;

    }

    publicThread newThread(Runnable runnable){

       return new MyAppThread(runnable,poolName);

    }
}

public class MyAppThread extends Thread{

   public static final StringDEFAULT_NAME="MyAppThread";

   private static volatileboolean debugLifecycle=false;

   private static finalAtomicInteger created=new AtomicInteger();

   private static finalAtomicInteger alive=new AtomicInteger();

   private static final Loggerlog=Logger.getAnoymousLogger();

  

  public MyAppThread(Runnabler){this(r,DEFAULT_NAME);}  

   public MyAppThread(Runnablerunnable,String name){

     super(runnable,name+"-"+created.incrementAndGet());

      setUncaughtExceptionHandler(newThread.UncaughtExceptionHandler(){

          public void uncaughtException(Thread t,Throwable e){

                  log.log(Level.SEVERE,"UNCAUGHTin thread"+t.getName(),e);

          }

     });

   }

  

   public void run(){

       boolean debug=debugLifecycle;

       if (debug) log.log(Level.FINE,"created"+getName());

       try{

               alive.incrementAndGet();

               super.run();

        }

        finally{

            alive.decrementAndGet();

            if (debug)log.log(Level.FINE,"Exiting"+getName());             

       }

   }

  

   public static intgetThreadsCreated(){return created.get();}

   publicstatic int getThreadsAlive(){return alive.get();}

   public static booleangetDebug(){return debugLifecycle;}

   public static voidsetDebug(boolean b){debugLifecycle=b;}

}

你可能感兴趣的:(java,thread)