线程的创建和销毁都会消耗很大的资源,如果有很多短时间的任务,如果为每个任务创建新线程, 创建和销毁线程上花费的时间和消耗的系统资源要比花在处理实际的用户请求的时间和资源更多,除了线程的创建和销毁外,活跃的线程也消耗系统资源,比如线程间的切换(线程超过一定数量后,系统的效率会急剧下降),每个线程私有栈所耗内存,所以,系统中线程的数量也要有控制, 因此引入了线程池的概念。
建立线程池
新建立一个线程池,一般使用util.concurrent包下面的Executors.java类
/**create 线程池的最基本的类 *corePoolSize: 线程池中保持存活的线程数,包括idle的; *MaximumPoolSize: 线程池中最大的线程数量 *keepAliveTime: 当线程池中线程的数量超过corePoolSize时,多余的线程idle达到keepAliveTime时间后会终止,unit是该事件的时间单位 *workQueue:工作队列,该工作队列,用来存放已经被submit去execute,但还没有分到线程的runable或者callable的task数据,默认的队列大小是Integer.MAX_VALUE *threadFactory:用来生成一个新线程的地方,见接口ThreadFactory的定义,包括定义新线程的name, priority, daemon */ public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory);(下面简称default) //create一个固定大小的线程池,后面一种有coder自己制定ThreadFactory创建新线程的方式,前面一种采用DefaultThreadFactory来创建, 该创建方式在内部实际是调用default的方式来创建,只是corePoolSize和MaximumPoolSize相等,都是等于nThreads public static ExecutorService newFixedThreadPool(int nThreads) ; public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory); //create一个只有一个工作线程的线程池,当这个线程由于exception或者failture导致terminates,另外new一新线程来执行新的任务(如果一个线程在等待某一资源比如,I/O的时候,该如何处理?),内部也是调用default的方式,只是corePoolSize和MaximumPoolSize的尺寸都是为1 public static ExecutorService newSingleThreadExecutor(); public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory); //create一个按需create新线程的线程池,内部是对default的封装,corePoolSize=0,MaximumPoolSize=Integer.MAX_VALUE, keepAliveTime=60s,在很多短执行时间的异步任务的情景比较能提高程序的效率 public static ExecutorService newCachedThreadPool(); public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory); //这四个是create一个线程Executor,用来执行一个周期性的或者延迟性的命令或task,其中前两种是对后两种的封装,将corePoolSize的值set为1 public static ScheduledExecutorService newSingleThreadScheduledExecutor(); public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory); public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize); public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory); //还有其他的一些封装 public static ExecutorService unconfigurableExecutorService(ExecutorService executor); public static ScheduledExecutorService unconfigurableScheduledExecutorService(ScheduledExecutorService executor); static class PrivilegedThreadFactory extends DefaultThreadFactory static class DelegatedExecutorService extends AbstractExecutorService;
public interface ThreadFactory { Thread newThread(Runnable r); }
线程池的参数的确定:
主要是线程池大小的确定。确定线程池的大小,首先要考虑的因素,是同时有多少任务要运行,有没有资源阻塞,
参考文档: