構造方法
ThreadPoolExecutor總共有四個構造方法
下面這個是最核心的,其他三個都基於該構造方法來構造。
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;
}
可以看到構造方法中總共有7個參數,分別看看是什麼意思
執行流程
當你使用線程池去執行任務時,線程池會以下面的流程去執行。
需要注意的是,如果線程池中線程的數量小於corePoolSize
,即使線程池中的線程都處於空閒狀態,也要創建新的線程來處理被添加的任務。