线程池的规则与参数: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实现定时执行。