线程池创建参数介绍:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
corePoolSize
: 线程池中核心线程的数量。
maximumPoolSize
:线程池中最大线程数量。
keepAliveTime
:非核心线程的超时时长,当系统中非核心线程闲置时间超过keepAliveTime之后,则会被回收。如果ThreadPoolExecutor的allowCoreThreadTimeOut属性设置为true,则该参数也表示核心线程的超时时长。
unit
:keepAliveTime这个参数的单位,有纳秒、微秒、毫秒、秒、分、时、天等。
workQueue
:线程池中的任务队列,该队列主要用来存储已经被提交但是尚未执行的任务。存储在这里的任务是由ThreadPoolExecutor的execute方法提交来的。
threadFactory
:为线程池提供创建新线程的功能,这个我们一般使用默认即可。
handler
: 拒绝策略,当线程无法执行新任务时(一般是由于线程池中的线程数量已经达到最大数或者线程池关闭导致的),默认情况下,当线程池无法处理新线程时,会抛出一个RejectedExecutionException。
四种常见的线程池:
FixedThreadPool:
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(task);
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
数量固定的线程池,核心线程数等于最大线程数,即只有核心线程。
CachedThreadPool:
ExecutorService executorService1 = Executors.newCachedThreadPool();
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
没有核心线程,只有非核心线程,最大线程数量是Integer.MAX_VALUE,实际就是代表非核心线程数量任意大。任务队列是一个空集合,表示任何任务都会被立即执行。
这类线程池适合执行大量的耗时少的任务。
但是存在一个问题:线程太多会占用内存资源,导致OOM,所以不建议使用
ScheduledThreadPool:
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE,
DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
new DelayedWorkQueue());
}
核心线程数是固定的,非核心线程数量没有限制,是Integer.MAX_VALUE。这类线程池主要用于执行定时任务和具有固定周期的重复任务。
也是存在一个问题,线程太多占用内存资源,会导致OOM,所以也是不建议使用
SingleThreadPool:
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
单线程线程池,核心线程数和最大线程数量都是1,所以就是个单线程,但是任务可以有多个,所有的任务都是在同一个线程中按顺序执行。不需要考虑线程同步的问题。也没有超时机制。
问:为什么不推荐使用几种固定线程池?
是因为固定线程池中存在最大线程数设置为无限大,这种存在的问题就是会导致内存消耗很大,导致OOM。