继续来学习Doug Lea大神的代码
线程池
线程池的状态:
RUNNING: Accept new tasks and process queued tasks
SHUTDOWN: Don’t accept new tasks, but process queued tasks
STOP: Don’t accept new tasks, don’t process queued tasks,
and interrupt in-progress tasks
TIDYING: All tasks have terminated, workerCount is zero,
he thread transitioning to state TIDYING
will run the terminated() hook method
TERMINATED: terminated() has completed
RUNNING -> SHUTDOWN:shutdown()
SHUTDOWN -> TIDYING:队列和线程池均为空
STOP -> TIDYING:线程池为空
TIDYING -> TERMINATED:terminated()
最核心的构造函数:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
corePoolSize:线程池中最大的核心线程的数量,核心线程即为即使处于等待状态也不会被销毁的线程
maximumPoolSize:线程池允许的最大线程数
keepAliveTime:当线程池中线程数量大于核心线程数量时,工作线程的最大等待时间,过了等待时间工作线程会被终止
unit:时间的单位
workQueue:任务被处理之前等待的队列
threadFactory:线程工厂
handler:当线程池和阻塞队列全部满的时候对新任务的处理方式
execute
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* 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.
*/
int c = ctl.get();
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);
}
1、如果线程池内线程数小于corePoolSize,则每来一个任务就新建一个核心线程去处理;
2、如果线程池内线程数小于corePoolSize,小于maximumPoolSize,往阻塞队列插入任务;
3、如果2中插入失败,那么直接添加一个工作线程来处理;
4、如果2中插入成功,等待空闲线程来取任务执行,如果线程池线程数为0,添加一个线程来处理任务;如果线程池不处于运行状态并且任务删除成功,拒绝后面的任务。
参考资料
jdk 1.8中的线程池 作者: EnjoyCodingEnjoyLife
java6的实现 作者: Matrix海子