我们使用如下的demo来一步一步分析线程池
public class TheadPoolTest {
public static void main(String[] args) throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(2);
// ExecutorService service = Executors.newCachedThreadPool();
// ExecutorService service = Executors.newWorkStealingPool();
for (int i = 0; i < 4; i++) {
service.submit(getTask());
//如果都是不需要返回结果的Runnable可以直接使用
//service.execute(getTask());
}
}
private static Runnable getTask() {
return new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getId());
}
};
}
}
Executors是一个工厂类,里面封装了多个用于创造特定场景下使用的线程池的工厂方法。比如我们示例中的Executors.newFixedThreadPool(2)会返回一个固定线程个数的线程池。详细来看看
//Executors:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue());
}
//ThreadPoolExecutor:
private static final RejectedExecutionHandler defaultHandler =
new AbortPolicy();
private static final RuntimePermission shutdownPerm =
new RuntimePermission("modifyThread");
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue 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;
}
ThreadPoolExecutor是真正构造线程池的类。其中的参数解释如下:
核心线程数,线程池中会长期保留的线程,即使线程池中有多个空闲线程,但是线程总数没有达到corePoolSize,新任务提交后也会再次创建一个新的线程去处理任务。
超过这个corePoolsize数量的线程会在一段时间的空闲后被清理掉。
int maximumPoolSize
线程池中同时运行的线程最大的总数量
long keepAliveTime
超过coerPoolSize的线程处于idle状态时,允许存活的最大时间。这样能减少大量空闲线程对资源的消耗。
TimeUnit unit keepAliveTime的时间单位
BlockingQueue workQueue 阻塞队列,用来存放提交过来的Runable任务
几种常见的策略
Unbounded queues(无界队列):
使用一个无界的队列来存放任务(比如, 使用new LinkedBlockingQueue(),默认容量是Integer.Integer.MAX_VALUE),当新的任务被提交,线程数已经达到了coreSize,
这是不会再产生任何新的线程,任务都会入队,直到coreThreads有可用的。
这种时候任务之间相互独立的场景,如web页面请求任务。
Bounded queues(有界队列):
一个有界队列(ArrayBlockingQueue)通过合理设置maxnumPoolSize以防止资源被过度消耗,这种对任务的管理方式
更难于调控。队列的size与线程池maxSize之间需要相互协调妥协:大队列和小线程池可以减少CPU\OS资源\上线问切换的消耗。
但是会导致较低的吞吐量。 如果任务频繁的阻塞(比如密集的IO,IO成为瓶颈),CPU也许导致大量空闲资源。
然而小队列大线程池,CPU可以充分利用,但是频繁的线程调度上下文切换同样会导致吞吐量下降。
ThreadFactory threadFactory 用来创建线程池中线程的工厂类,可以设置daemon状态、线程名称、线程组以及优先级等信息
RejectedExecutionHandler handler
ThreadPoolExecutor.AbortPolicy(默认,拒绝策略)
当线程池没有空余线程、并且队列已经满了。这时候会默认采取拒绝策略,
丢弃任务并抛出RejectedExecutionException
ThreadPoolExecutor.CallerRunsPolicy
CallerRunsPolicy会使用当前提交任务的线程去执行任务,这种策略会导致任务提交的速度下降。
ThreadPoolExecutor.DiscardPolicy
DiscardPolicy简单来说就是直接丢弃任务,没有任何反馈。
/**
*mainLock用来同步 woker set的访问 和 相关的记录
*/
private final ReentrantLock mainLock = new ReentrantLock();
/**
* Set containing all worker threads in pool. Accessed only when holding
* mainLock.
* 看到了,线程的这个池子就是用ReentrantLock维护的HashSet
*/
private final HashSet workers = new HashSet();
//(Executors父类) AbstractExecutorService
public Future> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
//将Runnable task包装为一个 FutureTask类型
protected RunnableFuture newTaskFor(Runnable runnable, T value) {
return new FutureTask(runnable, value);
}
/**FutureTask:
*
* 实现了Runnable接口、Future接口
* 一个可 取消的 异步的计算任务。
* 这个类实现了Future基本功能:启动、取消一个计算任务;
* 查看这个计算任务是否执行完毕;
* 查看计算结果(在计算完毕之后)。
* get()获取执行的计算结果,如果计算没有执行完毕,那么会产生park阻塞。
*
* FutureTask可以用来包装 Callable或者Runnable对象。
**/
//ThreadPoolExecutor.execute(Runnable command)
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
// 获取ctl的大小.ctl中包装了workerCount、runState两个变量
int c = ctl.get();
// Step1
// 如果池中的线程数少于corePoolSize,尝试创建一个新的线程去执行这个command.
if (workerCountOf(c) < corePoolSize) {// 通过位运算获取workerCount。如果workerCount
if (addWorker(command, true))// 创新新的线程执行command任务。
return;
c = ctl.get();
}
// Step2
// 如果这个任务可以成功入队,再次对线程池运行状态检查:这里使用了一个无界队列(实际上是Integer.Max)
if (isRunning(c) && workQueue.offer(command)) {// 任务入队
int recheck = ctl.get();
// 如果线程池已经处于非运行状态,
// 那么移除并使用handler处理这个任务
if (!isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
// Step3
// 如果入队失败,那么我们尝试新增一个线程。
// 如果新增失败,那么应该是线程池关闭了或者已经饱和了。那么我们最终拒绝这个任务。
else if (!addWorker(command, false))
reject(command);
}
//ThreadPoolExecutor.addWorker(Runnable firstTask, boolean core)
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);// 解包装获取workerCount
// workerCount>=CAPACITY || workerCount>=
if (wc >= CAPACITY || wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))// CAS workerCount+1
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);//将这个Task作为参数,初始化一个Woker
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();//启动woker线程
workerStarted = true;
}
}
} finally {
if (!workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
//ThreadPoolExecutor.Worker
//Woker是ThreadPoolExecutor的内部类,继承了AQS(其中实现了一个简单的排他锁,不可重入)、实现了Runnable.
//Woker中创建了一个线程,处理完首个任务后会从队列头部获取入队的任务继续执行
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
/** Delegates main run loop to outer runWorker */
public void run() {
runWorker(this);
}
//ThreadPoolExecutor
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
//默认state==-1,为-1的时候阻塞线程中断。此次将-1设置为0,运行线程在执行期间响应中断ts
w.unlock();
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);//hook befoer TaksExecute
Throwable thrown = null;
try {
task.run();//FutureTask.run—>Callable.run——>Runnable.run;运行结束后在FutureTaks中设置result.
} 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);
}
}
java.util.concurrent.ThreadPoolExecutor.ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
Step1:如果线程池中线程数量没有超过coreSize,则继续创建新的线程(全局锁);否则执行Step2
全局锁
/**
* Lock held on updates to poolSize, corePoolSize,
* maximumPoolSize, runState, and workers set.
*/
private final ReentrantLock mainLock = new ReentrantLock();
Step2 : 如果线程池中线程数量超过coreSize,则把这个任务放入阻塞队列中(BlockingQueue workQueue 尾部)
Step3 : 如果阻塞队列满了,则查看是否达到线程池最大线程数,如果没有继续创建新线程(全局锁)执行这个任务;否则Step4 使用RejectedExecutionHandler拒绝策略处理任务。
Step4 : 使用拒绝策略处理任务:
AbortPolicy:直接抛出RejectException异常
DiscardPolicy:直接丢弃这个任务
DiscardOldestPolicy:丢弃任务队列中的头部的任务,然后放入当前任务
CallerRunsPolicy: 直接用当前线程执行该任务
当线程池完成预热后(threadSize>coreSize),每次任务进入都会执行Step2,放入阻塞队列中,避免了获取全局锁。
ThreadPoolExecutor.execute(Runnable command)源码:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {
if (runState == RUNNING && workQueue.offer(command)) {
if (runState != RUNNING || poolSize == 0)
ensureQueuedTaskHandled(command);
}
else if (!addIfUnderMaximumPoolSize(command))
reject(command); // is shutdown or saturated
}
}
ThreadPoolExecutor.addThread(Runnable firstTask)-新创建线程
private Thread addThread(Runnable firstTask) {
Worker w = new Worker(firstTask);
Thread t = threadFactory.newThread(w);
boolean workerStarted = false;
if (t != null) {
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
w.thread = t;
workers.add(w);
int nt = ++poolSize;
if (nt > largestPoolSize)
largestPoolSize = nt;
try {
t.start();
workerStarted = true;
}
finally {
if (!workerStarted)
workers.remove(w);
}
}
return t;
}
线程池会把收到的Runnable任务封装为封装为Worker对象(implements Runnable),在这个woker里执行,当这个收到的任务执行完,会继续执行阻塞队列里的其他任务(从头部获取新任务).
execute()\submit() shutDown\shutDownNow
execute执行runnable任务,没有返回值。submit会返回Future对象,future对象get()方法阻塞式获取执行后返回的结果。
shutDown\shutDownNow都是遍历所有线程,依次执行interrupt操作
Executors使用静态工厂返回特定类型的线程池:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue());
}
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue(),
threadFactory);
}
keepAliveTime设置为0,表示超过coreThread数量的线程会立刻被终止。
FixedThreadPool使用了LinkedBlockingQueue()这个无界的阻塞队列,表示达到了coreThread数量后,新进入的任务总是会放入任务队列中,不会创建多余的线程,线程数量不会超过coreThread数量。因此也不涉及到任何对任务的丢弃等处理策略。
它限定了线程的数量,适用于需要控制资源的使用,负载较重的机器。
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue());
}
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue(),
threadFactory);
}
CacheThreadPool对线程数量基本没有限制(Integer.MAX_VALUE),它使用了SynchronousQueue作为线程池的任务队列
具体执行情况:
SynchronousQueue是个没有容量的阻塞队列,每个插入操作必须等待另一个线程的移除操作,反之亦然。移除与插入的两个线程必须对应。
CacheThreadPool是个无限制的线程池,适用于 执行任务多,每个任务执行时间短或负载较轻的机器