線程池的規則與參數:java
1. corePoolSize:核心線程數線程
2. queueCapacity:任務隊列容量(阻塞隊列)code
3. maxPoolSize:最大線程數隊列
4. keepAliveTime:非核心線程空閒時間ci
5. allowCoreThreadTimeout:容許核心線程超時it
6. rejectedExecutionHandler:任務拒絕處理器io
幾類型線程池class
1. FixedThreadPool thread
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); }
核心池等於最大池大小,隊列無界;核心線程不會退出。線程池
2. SingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
核心池等於最大池=1,隊列無界;保證任務串行執行,當線程由於異常終止,會啓動新線程執行;該線程不會超時退出。
3. CachedThreadPool
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory); }
核心池大小是0,最大池大小無上界,隊列無界;線程60s超時退出。適合短時間執行的大量任務。SynchronousQueue是一個容量只有1的阻塞隊列。
4. ScheduledThreadPool
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); } public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue()); }
使用DelayQueue實現定時執行。