Jdk源码详解之ThreadPoolExecutor 类

1.类释义

An ExecutorService that executes each submitted task using
one of possibly several pooled threads, normally configured
using Executors factory methods.

一个ExecutorService(线程池),用于执行每个提交的任务,使用可用线程池的多个线程中的一个线程,常用的正常配置是:使用Excutors 的工厂方法。

2.类代码

ThreadPoolExecutor

public class ThreadPoolExecutor extends AbstractExecutorService {...}

3.主要方法

  • 构造函数:​​ThreadPoolExecutor()​
/**
Creates a new ThreadPoolExecutor with the given initial
parameters and default rejected execution handler.
使用初始化参数,和默认的拒绝执行处理程序创建一个新的ThreadPoolExecutor。

@param corePoolSize the number of threads to keep in the pool, even
if they are idle, unless allowCoreThreadTimeOut is set
留在线程池中的线程数,即使他们都是闲置的。除非allowCoreThreadTimeOut被设置。

@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
keepAliveTime这个参数的单位

@param workQueue the queue to use for holding tasks before they are
executed. This queue will hold only the Runnable
tasks submitted by the execute method.
未执行任务的保存队列。这队列将会被保留,这个队列仅仅保存由execute()方法提交的任务。

@param threadFactory the factory to use when the executor creates a new thread
当executor创建一个新的进程时,会使用到的一个工厂

@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} is null
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, defaultHandler);
}

可以看到这里的​​BlockingQueue()​​​是一个queue,用于保存即将执行的任务。这个 ​​BlockingQueue​​​接口的主要实现类有:​​ArrayBlockingQueue​​,

public class ArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
...
}

​ArrayBlockingQueue​​类的释义如下:

A bounded BlockingQueue(blocking queue) backed by an array.
一个有界限的Blocking queue,底层是一个array。