目录
一、ThreadPoolExecutor简介
ThreadPoolExecutor是我们在Java中常用的线程池类,当然我们经常用如下方法创建,但是这些方法内部最终还是通过ThreadPoolExecutor构造的。(所以我有时候很不理解,为什么一说直接用ThreadPoolExecutor构造线程池,有些人就很排斥?难道不觉得很灵活么?难道不觉的那几个工厂方法试用的场景有限么?)
Executors.newFixedThreadPool
Executors.newSingleThreadExecutor
Executors.newCachedThreadPool
ThreadPoolExecutor的构造函数说明如下:
public ThreadPoolExecutor(
int corePoolSize, // 线程池的核心线程数,会在空闲期也最少持有该线程数
int maximumPoolSize, // 最大线程数。当线程池的线程实在不够用的时候(当queue放不下的时候)会增加pool持有的线程资源数量。当总thread数量超过orePoolSize时thread空闲时间超过就会被释放掉。
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue, // 任务队列
ThreadFactory threadFactory, // ThreadFactory在线程池创建线程时调用threadFactory.newThread生成新的线程
RejectedExecutionHandler handler // 当队列满了并且maximumPoolSize达到了最大数时,对新增任务的拒绝策略。
)
参数用处说明:
1.当线程池小于corePoolSize时,新提交任务将创建一个新线程执行任务,即使此时线程池中存在空闲线程。
2.当线程池达到corePoolSize时,新提交任务将被放入workQueue中,等待线程池中任务调度执行
3.当workQueue已满,且maximumPoolSize>corePoolSize时,新提交任务会创建新线程执行任务
4.当提交任务数超过maximumPoolSize时,新提交任务由RejectedExecutionHandler处理
5.当线程池中超过corePoolSize线程,空闲时间达到keepAliveTime时,关闭空闲线程
6.当设置allowCoreThreadTimeOut(true)时,线程池中corePoolSize线程空闲时间达到keepAliveTime也将关闭
RejectedExecutionHandler 有四种实现(源码都很简单我只说作用不在重复源码了):
AbortPolicy:丢弃任务并抛出RejectedExecutionException异常
DiscardPolicy:直接丢弃任务
DiscardOldestPolicy:丢弃任务队列顶端的任务,然后吧新任务加入
CallerRunsPolicy:主线程(调用execute方法的线程)自己执行
二、运行原理
为方便描述图中是简化过的逻辑,源码分析的会补全丢下的逻辑。
执行execute时的流程如下:
worker自动运行流程如下:
三、源码分析
通过如上流程图就可以基本了解线程池的运行原理了。那么我们继续了解一下源码:
从execute(Runnable command)方法源码是提交任务的入口开始:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
// 如果 当前持有thread资源小于corePoolSize数尝试新建一个线程
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))// 这里addworker第二个参数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);// 这里addworker第二个参数true表示添加的是非核心线程,受最大线程数限制
}
// 如果不能加入到队列中
else if (!addWorker(command, false))
reject(command); // look at this 这就是我们之前设置的拒绝策略
}
先看一个最简单的方法reject源码如下:
final void reject(Runnable command) {
handler.rejectedExecution(command, this);
}
这里就是简单的调用一下构造参数RejectedExecutionHandler。
看一下addWorker()方法:
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);
// 如果thread资源超过corePoolSize或者超过maximumPoolSize添加失败
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
// 增加 workerCount 计数器,然后跳出循环,新增worker
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 {
// 新建worker
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;
}
大概意思就是在小于指定线程数的情况下创建一个worker。worker来取完成我们提交的任务。这个worker就是threadPool的处理中心了。
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);// 这里就是我们配置的threadFactory
}
public void run() {
runWorker(this);
}
// 执行worker
final void runWorker(ThreadPoolExecutor.Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
// 如果能获取到任务那么一直运行getTask是一个阻塞等待的方法
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(); // 运行我们提交的runnable任务。
} 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);
}
}
// 获取任务
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?
// 是否允许核心线程超时,如果允许的话核心线程也一样会狗带
// 核心线程允许超时或者当前worker数大于核心线程数
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
// 超时没有获取到任务返回空然后会终止worker的while循环然后这个worker就狗带了
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
// 阻塞从blockingqueue中获取任务
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
通过如上代码可以看出线程池其实就是new了一堆线程,这些线程一直循环的处理我们提交的runnable,从而达到了线程复用的效果。
四、扩展
1.ThreadPoolExecutor确实很灵活但是也带来了一些麻烦。比如:
new ThreadPoolExecutor(10, 100, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
用如上的代码去创建一个线程池的时候可能达不到我们想要的效果,最大线程数基本不会用上。因为我们使用了一个“无界队列”。所以在使用“无界队列”的时候核心和最大线程数要设置一致呦。
如果又想要线程的伸缩能力,这个时候怎么办呢?上边源码中的allowCoreThreadTimeOut就显现了用处。
ThreadPoolExecutor executor = new ThreadPoolExecutor(100, 100, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
executor.allowCoreThreadTimeOut(true);
这样即获得了大量存储任务的能力也具worker伸缩的能力,适合应用在一些特定的场景。
2.上边的beforeExecute(wt, task);和afterExecute这两个“糊弄人”的方法,其实是模版中可以实现自定义的方法。可以根据自身情况重写这两个方法就可以在任务执行的前后做一些不可描述的事情。
3.创建一个任务队列满了一直等待任务放入任务队列的线程池
new ThreadPoolExecutor(10, 20, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(15),
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
// block until there's room
executor.getQueue().put(r);
} catch (InterruptedException e) {
throw new RejectedExecutionException("Unexpected InterruptedException", e);
}
}
});
五、ScheduledThreadPoolExecutor
队列使用堆实现优先级队列,来实现任务排序
public ScheduledThreadPoolExecutor(int corePoolSize,
RejectedExecutionHandler handler) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue(), handler);
}
插入任务的时候会通过如下方法进行周期或延迟执行
private void delayedExecute(RunnableScheduledFuture<?> task) {
if (isShutdown())
reject(task);
else {
super.getQueue().add(task);
if (isShutdown() &&
!canRunInCurrentRunState(task.isPeriodic()) &&
remove(task))
task.cancel(false);
else
ensurePrestart();
}
}
ScheduledFutureTask的run方法实现了周期执行
public void run() {
boolean periodic = isPeriodic();
if (!canRunInCurrentRunState(periodic))
cancel(false);
else if (!periodic)
ScheduledFutureTask.super.run();
else if (ScheduledFutureTask.super.runAndReset()) {
setNextRunTime();
reExecutePeriodic(outerTask);
}
}
如果是周期任务会执行 setNextRunTime和reExecutePeriodic重置执行时间。
获取执行任务逻辑如下:
public RunnableScheduledFuture<?> take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
for (;;) {
RunnableScheduledFuture<?> first = queue[0];
if (first == null)
available.await();
else {
long delay = first.getDelay(NANOSECONDS);
if (delay <= 0)
return finishPoll(first);
first = null; // don't retain ref while waiting
if (leader != null)
available.await();
else {
Thread thisThread = Thread.currentThread();
leader = thisThread;
try {
available.awaitNanos(delay);
} finally {
if (leader == thisThread)
leader = null;
}
}
}
}
} finally {
if (leader == null && queue[0] != null)
available.signal();
lock.unlock();
}
}
队列的take方法会通过available.awaitNanos(delay)和available.await()阻塞获取需要执行的任务达到延迟效果。
public boolean offer(Runnable x) {
if (x == null)
throw new NullPointerException();
RunnableScheduledFuture<?> e = (RunnableScheduledFuture<?>)x;
final ReentrantLock lock = this.lock;
lock.lock();
try {
int i = size;
if (i >= queue.length)
grow();
size = i + 1;
if (i == 0) {
queue[0] = e;
setIndex(e, 0);
} else {
siftUp(i, e);
}
if (queue[0] == e) {
leader = null;
available.signal();
}
} finally {
lock.unlock();
}
return true;
}
放入任务的时候会通过available.signal()方法唤醒,重新等待。