锁定老帖子 主题:线程工厂
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2010-02-24
线程池的作用:
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;} } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
浏览 1487 次