1.ThreadPoolExecutor
/**
* 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
*/
//构造函数有多个,这里选的最全的
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;
}
2.线程池处理流程
使用方提交任务。
线程池判断核心线程池是否已满,没满创建新线程执行任务,满了判断阻塞队列是否已满,没满将任务存储在阻塞队列,满了判断线程池是否已满,没满创建新线程执行任务,满了按照饱和策略处理多余的。
3.阻塞队列
有界队列: ArrayBlockingQueue、LinkedBlockingQueue
同步移交阻塞队列:SynchrousQueue
4.常用线程池
线程数量无限线程池
newCachedThreadPool,使用的SynchrousQueue
线程数量固定线程池
newFixedThreadPool,使用的LinkedBlockingQueue
单一线程线程池
newSingleThreadExecutor,使用的LinkedBlockingQueue
5.线程池状态
RUNNING
SHUTDOWN
TIDYING
STOP
TERMINATED