線程的建立和銷燬都會消耗很大的資源,若是有不少短期的任務,若是爲每一個任務建立新線程, 建立和銷燬線程上花費的時間和消耗的系統資源要比花在處理實際的用戶請求的時間和資源更多,除了線程的建立和銷燬外,活躍的線程也消耗系統資源,好比線程間的切換(線程超過必定數量後,系統的效率會急劇降低),每一個線程私有棧所耗內存,因此,系統中線程的數量也要有控制, 所以引入了線程池的概念。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