目录
学习目标:
1、线程池的属性学习
2、参考资料,源码学习
学习内容:
1、线程池属性
线程池的构造函数
/**
* 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.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
参数简介(参考构造方法注释及相关博客,个人理解,有错请指出):
-
corePoolSize:核心线程数,除非设置 allowCoreThreadTimeOut 属性,否则核心线程数创建后一直存在。核心线程数的创建过程为需要时,一个一个创建,非一次性创建。
-
maximumPoolSize:最大线程数,线程池中,最大可同时存在的线程数。
-
keepAliveTime:大于核心线程数的、空闲的(idle)线程等待回收的时间。
-
unit:keepAliveTime的时间单位。
-
workQueue:存放待执行的任务的队列。
-
threadFactory:线程工厂
-
handler:拒绝策略,当核心线程—>队列—>最大线程数都达到最大值时。资源即达到设置的最大值,如新加入任务时,则根据handler的策略,进行后续处理。
2、源码学习
线程池使用例子:
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFor