什么是线程池
线程池是提前创建若干线程进行任务处理,线程处理完任务不会销毁,而是继续等待处理其他任务。
使用场景
针对处理数据巨大且执行时间短的任务,出于对性能的要求,如果频繁创建大量线程,将会导致以下问题:
1)频繁创建、销毁线程,影响性能
2)线程总数如果超过操作系统限制,将会导致死机或内存溢出异常
因此针对这种场景,应该采用线程池,创建一定数量的线程,依次对任务进行处理。
线程池种类
1)固定线程池
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
2)缓存线程池
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
3)单线程线程池
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
4)调度线程池
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
线程池创建
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
1)corePoolSize
核心线程数,默认一直存活,当allowCoreThreadTimeOut设置为true时,核心线程将受keepAliveTime限制
2)maximumPoolSize
最大线程数,针对无界队列,该值无效
3)keepAliveTime
非核心线程超时时间,超时被回收
4)unit
时间单位,如TimeUnit.SECONDS
当allowCoreThreadTimeOut设置为true时,对核心线程生效
5)workQueue
任务队列,常有SynchronousQueue,LinkedBlockingQueue,ArrayBlockingQueue
6)threadFactory
线程工厂,默认为DefaultThreadFactory
7)handler
拒绝线程处理器,默认为AbortPolicy
线程池规则
假设任务数为n,有界任务队列LinkedBlockingQueue,则:
1)corePoolSize >= n,直接创建线程处理任务
2)corePoolSize < n,任务放到任务队列中
3)任务队列满,且maximumPoolSize >= n,直接创建线程处理任务
4)maximumPoolSize < n,拒绝处理任务抛出异常
如果任务队列为SynchronousQueue,corePoolSize < n,线程池会创建新线程处理任务,直至maximumPoolSize < n,拒绝处理抛出异常。