线程池的作用:
线程池作用就是限制系统中执行线程的数量。
根据系统的环境情况,可以自动或手动设置线程数量,达到运行的最佳效果;少了浪费了系统资源,多了造成系统拥挤效率不高。用线程池控制线程数量,其他线程排队等候。一个任务执行完毕,再从队列的中取最前面的任务开始执行。若队列中没有等待进程,线程池的这一资源处于等待。当一个新任务需要运行时,如果线程池中有等待的工作线程,就可以开始运行了;否则进入等待队列
为什么要用线程池:
1. 减少了创建和销毁线程的次数,每个工作线程都可以被重复利用,可执行多个任务
2. 可以根据系统的承受能力,调整线程池中工作线线程的数目,防止因为因为消耗过多的内存,而把服务器累趴下(每个线程需要大约1MB内存,线程开的越多,消耗的内存也就越大,最后死机)
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;}
}