线程池
java中通过Executors.newXXXThreadPool()来创建各种类型的线程池,最常见的有下面三种线程池
- CachedThreadPool
- FixedThreadPool
- SingleThreadPool
下面看下三个方法的源码
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
上面三个方法都提供了指定ThreadFactory的重载版本,ThreadFactory是用来创建Thread的
简单地看一下上面的源码,都是创建并且返回了ThreadPoolExecutor对象,不同的是传入的参数
接着看一下ThreadPoolExecutor的源码来看一下这些参数都是用来做什么的
ThreadPoolExecutor主要有以下属性:
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
private static final int COUNT_BITS = Integer.SIZE - 3;
private static final int CAPACITY = (1 << COUNT_BITS) - 1;
// runState is stored in the high-order bits
// 高三位为111
private static final int RUNNING = -1 << COUNT_BITS;
// 高三位为000
private static final int SHUTDOWN = 0 << COUNT_BITS;
// 高三位为001
private static final int STOP = 1 << COUNT_BITS;
// 高三位为010
private static final int TIDYING = 2 << COUNT_BITS;
// 高三位为011
private static final int TERMINATED = 3 << COUNT_BITS;
// 所以不同状态clt值排序为
// TERMINATED > TIDYING > STOP > SHUTDOWN > RUNNING
private volatile int corePoolSize;
private volatile int maximumPoolSize;
private final BlockingQueue<Runnable> workQueue;
private final HashSet<Worker> workers = new HashSet<Worker>();
使用一个AtomicInteger来同时表达线程池状态和当前线程池中线程的数量
使用AtomicInteger的高三位来表示线程池的状态,剩下的位数用来表示线程池中线程的个数
corePoolSize:代表线程池中存活线程的最少个数
maximumPoolSize:线程池的最大容量
workQueue:待执行任务队列,线程会从这个队列中获取接下来需要执行的任务
workers:保存着线程池中的所有线程
因为我们需要执行execute()来向线程池提交任务,所以我们看一下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();
// 当前存活的线程个数少于corePoolSize,那么直接创建一个新的线程来执行当前的任务
if (workerCountOf(c) < corePoolSize) {
// 将corePoolSize作为线程池容量的上限,向线程池中添加线程
if (addWorker(command, true))
return;
c = ctl.get();
}
// 当前线程池正在运行并且当前线程池中的线程个数大于等于corePoolSize,那么将当前提交的任务添加到workQueue中
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
// 将maximumPoolSize作为线程池容量的上限,向线程池中添加线程
addWorker(null, false);
}
// workQueue中已经满了,无法再添加任务,那么我们就接着创建线程
// 如果创建线程失败,
else if (!addWorker(command, false))
reject(command);
}
接着看addWorker
// firstTask最为新创建线程第一个执行的任务
// core如果为true,那么使用corePoolSize作为边界,否则使用maximumPoolSize作为边界
// 该方法主要目的就是创建一个线程,并将其添加到线程池中
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
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);
// 如果当前线程数量大于边界,那么返回false
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
// 这里使用cas来修改ctl
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) {
// 当向线程池汇总添加线程时,需要竞争mainLock
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;
}
接下来看一下Worker的构造函数
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
// 使用线程工厂创建一个新的线程
// 另外因为Worker类本身实现了Runnable接口,可以作为线程执行的任务
this.thread = getThreadFactory().newThread(this);
}
public void run() {
runWorker(this);
}
// 线程实际执行的方法
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
// 首先会执行调用构造函数时传入的第一个任务,如果第一个任务完成了,就会调用getTask()从workQueue中获取新的任务
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);
}
}
接下来看一下getTask()
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
// 检查线程池状态
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
// Are workers subject to culling?
// 判是否需要使用计时
// 从这里可以看出当设置了allowCoreThreadTimeOut或者当前线程数量大于corePoolSize时会进行计时
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
// 线程数量大于maximumPoolSize 或者 需要使用计时并且计时时间已经到了
// 并且
// 线程数量大于1 或者 等待任务队列空了
// 这个时候就会返回null,注意以为getTask是线程执行主体的while循环中调用的,如果这里返回Null
// 那么runWorker()就会结束,而runWorker在结束的时候会将当前的worker从线程池中移除,相当于消除了一个线程
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
// 如果设置了等待计时
// 那么就会调用poll方法,等待一段时间,如果成功获取任务就返回,否则计时到时就会返回null
// 如果没有设置等待计时,就会一直等待下去
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
// 如果这次没有获得任务,就会标志等待超时
// 从而在一次新的循环中影响前面关于计时的判断
/*
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
*/
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
总结一下任务提交的流程:
(1)首先判断线程池中的线程数量是否小于corePoolsize,如果是,那么就会创建一个新的线程,而不会去管当前线程池中是否有空闲线程,否则,跳到(2)
(2)会尝试向任务等待队列中添加新的任务,如果任务等待队列已满就会跳到(3)
(3)如果当前线程池中的线程个数已经达到了maximumPoolSize,那么任务添加失败,会继而执行拒绝策略
通过上个面的分析,可以得出三种线程池的特点:
(1)FixedThreadPool
因为使用的是LinekedBlockingQueue,并且设置corePoolSize等于maximumPoolSize,并且不使用超时,因此每提交一个任务,首先判断线程池中的线程数量是否达到corePoolSize,如果没有达到,那么就创建一个新的线程来运行当前任务,否则将新的任务添加到任务等待队列中,并且这个队列是无界队列
(2)SingleThreadPool
是FixedThreadPool的特殊情况
(3)CachedThreadPool
corePoolSize设置为0,maximumPoolSize设置为Integer.MAX_VALUE,设置超时时间为60s
使用的是SynchronousQueue,该队列的特点是对该队列的插入操作和移除操作必须是成对的,向该队列进行插入操作会等待另外一个线程对该队列执行移除操作。最终的效果是,如果有新的任务到来时,首先使用当前空闲的线程来执行该任务,如果没有空闲的线程,那么就会创建新的线程,如果一个线程在60s内都没有接收到新的任务,那么就会销毁该线程