前言
我们使用线程池工具类,常用的newFixedThreadPool方法就是使用的ThreadPoolExecutor
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
下面来分析 ThreadPoolExecutor的参数
1、线程池的基本概念
线程池是一种容器的称呼,其实解释对象池的一种,线程池的设计遵循对象池的原则,比如我们可以使用commons-pool2自定义实现线程池。JDK自带线程池容器ThreadPoolExecutor。
2、线程池的主要参数
看源码,构造函数
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
* @param unit the time unit for the {@code keepAliveTime} argument
* @param workQueue the queue to use for holding tasks before they are
* executed. This queue will hold only the {@code Runnable}
* tasks submitted by the {@code execute} method.
* @param threadFactory the factory to use when the executor
* creates a new thread
* @param handler the handler to use when execution is blocked
* because the thread bounds and queue capacities are reached
* @throws IllegalArgumentException if one of the following holds:<br>
* {@code corePoolSize < 0}<br>
* {@code keepAliveTime < 0}<br>
* {@code maximumPoolSize <= 0}<br>
* {@code maximumPoolSize < corePoolSize}
* @throws NullPointerException if {@code workQueue}
* or {@code threadFactory} or {@code handler} is null
*/
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.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
2.1 核心线程
int corePoolSize:核心池大小
the number of threads to keep in the pool, even if they are idle, unless {@code allowCoreThreadTimeOut} is set
线程池在new 出来后是没有线程的,仅当执行任务的时候才会创建线程;
当然也可以调用线程池的prestartAllCoreThreads()方法,让线程池在创建时就创建corePoolSize数目的线程;
核心线程在任务完成时,会new 新的线程,并且不会销毁,除非设置allowCoreThreadTimeOut
public void allowCoreThreadTimeOut(boolean value) {
if (value && keepAliveTime <= 0)
throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
if (value != allowCoreThreadTimeOut) {
allowCoreThreadTimeOut = value;
if (value)
interruptIdleWorkers();
}
}
2.2 最大线程数
int maximuxPoolSize:最大线程池大小
the maximum number of threads to allow in the pool 线程池所允许创建的最大线程数;
2.3 存活时间
long keepAliveTime:线程存活时间
when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.
当线程池中的线程数量大于核心池大小后,超过核心数量的线程在keepAliveTime的时间内可以等待一个新任务,超过时间就会销毁;
TimeUnit timeUnit:keepAliveTime的单位,
unit the time unit for the {@code keepAliveTime} argument
TimeUnit 枚举值有:DAYS、HOURS、MINUTES、SECONDS、MILLISECONDS(毫秒)、MICROSECONDS(微秒)、NANOSECONDS(纳秒);
2.4 工作队列
BlockingQueue workQueue:阻塞任务队列
the queue to use for holding tasks before they are executed. This queue will hold only the {@code Runnable} tasks submitted by the {@code execute} method.
执行前的任务,存储在队列中(线程池会先使用核心线程,当核心线程用完才会使用队列);
线程池只会execute Runnable任务,Callable任务也会包装成Runnable任务
主要实现类有:
1)LinkedBlockingQueue:基于链表的无界(默认构造函数为:最大值Integer.MAX_VALUE容量)阻塞队列,按FIFO(先进先出)的规则存取任务
2)ArrayBlockingQueue:基于数组的有界阻塞队列,按FIFO的规则对任务进行存取,必须传入参数来定义队列大小
3)DelayedWorkQueue:基于堆的延迟队列,Executors.newScheduledThreadPool(...)中使用了该队列
4)PriorityBlockingQueue:具有优先级的阻塞队列
5)SynchronousQueue:不存储任务的阻塞队列,每一个存入对应一个取出,串行化队列
吞吐量:SynchronousQueue > LinkedBlockingQueue > ArrayBlockingQueue
2.5 线程创建工厂
ThreadFactory threadFactory:线程工厂
the factory to use when the executor creates a new thread
用来创建线程,可以通过自定义线程工厂给新创建的线程设置更合理的名字、设置优先级和是否守护线程
比如:Executors自定义的线程工厂实现
static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DefaultThreadFactory() {
SecurityManager s = System.getSecurityManager();
//线程组
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
//名称前缀,这就是我们打印的线程池中线程名称前缀
//可以修改的,如果自定义线程工厂
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}
//工厂创建线程
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon())
//非守护线程
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
//常规优先级
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
}
2.6 拒绝策略
RejectedExecutionHandler handler:拒绝任务的接口处理器
the handler to use when execution is blocked because the thread bounds and queue capacities are reached
达到队列和线程池的最大线程数限制,就执行拒绝策略
拒绝策略有:
1)AbortPolicy:拒绝任务并抛出异常,默认的策略
2)DiscardPolicy:直接拒绝不抛出异常
3)DiscardOldestPolicy:丢弃队列中最远的一个任务(最先进入队列的,FIFO),并执行当前任务;
4)CallerRunsPolicy:只用调用者所在的线程来执行任务,不管其他线程的事。
也可以自定义拒绝策略,来处理如传递持久化日志、存储不能处理的任务等自定义功能
自定义拒绝策略实现:实现RejectedExecutionHandler接口;覆写rejectedExecution()方法
----------------------------------------------------------------------------------
原文:https://blog.csdn.net/fenglllle/article/details/81129125