线程的建立和销毁都会消耗很大的资源,若是有不少短期的任务,若是为每一个任务建立新线程, 建立和销毁线程上花费的时间和消耗的系统资源要比花在处理实际的用户请求的时间和资源更多,除了线程的建立和销毁外,活跃的线程也消耗系统资源,好比线程间的切换(线程超过必定数量后,系统的效率会急剧降低),每一个线程私有栈所耗内存,因此,系统中线程的数量也要有控制, 所以引入了线程池的概念。java
创建线程池异步
新创建一个线程池,通常使用util.concurrent包下面的Executors.java类spa
/**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); }
线程池的参数的肯定:线程
主要是线程池大小的肯定。肯定线程池的大小,首先要考虑的因素,是同时有多少任务要运行,有没有资源阻塞, code
参考文档:blog