线程工厂

 

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

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

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

public class MyThreaadFactory implements ThreadFactory{

    private final String poolName;

   

    public  MyThreadFactory(String poolName){

        this.poolName=poolName;

    }

    public 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.getAnoymousLogger();

  

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

   public MyAppThread(Runnable runnable,String name){

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

      setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){

           public void uncaughtException(Thread t,Throwable e){

                  log.log(Level.SEVERE,"UNCAUGHT in 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 int getThreadsCreated(){return created.get();}

   public static int getThreadsAlive(){return alive.get();}

   public static boolean getDebug(){return debugLifecycle;}

   public static void setDebug(boolean b){debugLifecycle=b;}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值