目录
参数解释
public ThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler
)
corePoolSize
核心线程数。在创建了线程池后,线程中没有任何线程,等到有任务到来时才创建线程去执行任务。默认情况下,在创建了线程池后,线程池中的线程数为0,当有任务来之后,就会创建一个线程去执行任务,当线程池中的线程数目达到corePoolSize后,就会把到达的任务放到缓存队列当中。
maximumPoolSize
最大线程数。表明线程中最多能够创建的线程数量。
keepAliveTime
空闲的线程保留的时间。
TimeUnit
空闲线程的保留时间单位。
BlockingQueue<Runnable>
阻塞队列,存储等待执行的任务。参数有ArrayBlockingQueue、LinkedBlockingQueue、SynchronousQueue可选。
ArrayBlockingQueue和PriorityBlockingQueue使用较少,一般使用LinkedBlockingQueue和Synchronous。线程池的排队策略与BlockingQueue有关。
- 普通的阻塞队列:如ArrayBlockingQueue,LinkedBlockingQueue,PriorityBlockingQueue等,只要队列的容量足够就能成功入队。
- 其他阻塞队列:就是SynchronousQueue,它的成功入队表示有线程同时在接收入队的数据,有线程能处理入队数据。这里留下后文解释,这个是解线程复用的关键。
ThreadFactory
线程工厂,用来创建线程
RejectedExecutionHandler
队列已满,而且任务量大于最大线程的异常处理策略。有以下取值
- ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。
- ThreadPoolExecutor.DiscardPolicy:也是丢弃任务,但是不抛出异常。
- ThreadPoolExecutor.DiscardOldestPolicy:丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程)
- ThreadPoolExecutor.CallerRunsPolicy:由调用线程处理该任务
线程池实现原理
1. 线程池状态
ThreadPoolExecutor中定义了一个volatile变量,另外定义了几个static final变量表示线程池的各个状态:
- volatile int runState;
- static final int RUNNING = 0;
- static final int SHUTDOWN = 1;
- static final int STOP = 2;
- static final int TERMINATED = 3;
runState表示当前线程池的状态,它是一个volatile变量用来保证线程之间的可见性;
对于四个状态解释如下:
- 当创建线程池后,初始时,线程池处于RUNNING状态;
- 如果调用了shutdown()方法,则线程池处于SHUTDOWN状态,此时线程池不能够接受新的任务,它会等待所有任务执行完毕;
- 如果调用了shutdownNow()方法,则线程池处于STOP状态,此时线程池不能接受新的任务,并且会去尝试终止正在执行的任务;
- 当线程池处于SHUTDOWN或STOP状态,并且所有工作线程已经销毁,任务缓存队列已经清空或执行结束后,线程池被设置为TERMINATED状态。
2. 任务的执行-execute方法
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
/**
谷歌翻译:
执行一下3个步骤:
1.如果正在运行线程数少于corePoolSize,
尝试使用传入Runnable作为其第一个任务启动新线程。
对addWorker的调用以原子方式检查runState和workerCount,
因此通过返回false来防止在不应该添加线程时发生的错误警报。
2.如果任务可以成功如队列,那么我们仍然需要
仔细检查是否应该添加一个线程(因为自上次检查后现有的线程已经死亡),
或者自从进入此方法后池关闭了。
所以我们重新检查状态,如果必要的话,如果没有,则回滚入队,
或者如果没有,则启动新的线程。
3.如果我们不能排队任务,那么我们尝试添加一个新线程。
如果失败,我们知道我们已关闭或饱和,因此拒绝该任务。
*/
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
// 创建core核心线程-不涉及线程复用。
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
// 往队列里塞线程
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
代码比较短,是addworker方法
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
/* ctl是一个32位的线程池信息标识变量。
包含两个概念:
workerCount:表明当前有效的线程数
runState:表明当前线程池的状态,是否处于
Running,Shutdown,Stop,Tidying,Terminate五种状态。
*/
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
执行步骤:
1. 进入重试方法块(retry)
a.判断线程池是否已经shutdown,是则返回false
b.判断线程数是否大于了1<<29,是则返回false
c.判断线程数是否大于 corePoolSize or maximumPoolSize(根据core标志位区分),是则返回false
d.尝试增加workerCount,成功则跳出retry
e.重新获取runstatus,如果不为rs,则重新retry(a),否则重新尝试增加workerCount(b)
2. 新建worker对象,传入入参runnable
a.每个worker新建,都会创建一个线程
3.加锁
4.同步块执行:
a.判断状态是否为shutdown,如果是且worker对象线程存活,则抛出异常
b.往workers队列中添加worker
c.如果队列长度大于largestPoolSize,则更新largestPoolSize为队列长度值
d.启动worker中的线程:thread.start
5.小结
a.此时还没有结束。可以看到execute方法是新开线程的,怎么做到线程复用?
b.thread.start调用的是worker的run方法,run->runWorker方法是线程复用的关键
runWorker方法:
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
步骤如下:
a.进入while(对于核心线程默认来说是死循环,当前正在运行的线程数超出核心线程,getTask会返回null)(参数allowCoreThreadTimeOut配置为true,核心线程getTask也会返回null。细节可以自己参阅)
b.获取worker中的firstTask
c.如果没有,则调用getTask方法(核心线程被blockingqueue阻塞)
d.获取到了task,调用其run方法。
e.销毁task。(task=null)
f.重新获取task(b)
3. 线程复用大致原理
Worker本身是一个runnable,他自身的执行逻辑是从workQueue中取runnable来执行其run方法。