目录
学习目标:
学习内容:
1、线程池属性
2、源码学习
学习目标:
1、线程池的属性学习
2、参考资料,源码学习
学习内容:
1、线程池属性
线程池的构造函数
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;
}
参数简介(参考构造方法注释及相关博客,个人理解,有错请指出):
-
corePoolSize:核心线程数,除非设置 allowCoreThreadTimeOut 属性,否则核心线程数创建后一直存在。核心线程数的创建过程为需要时,一个一个创建,非一次性创建。
-
maximumPoolSize:最大线程数,线程池中,最大可同时存在的线程数。
-
keepAliveTime:大于核心线程数的、空闲的(idle)线程等待回收的时间。
-
unit:keepAliveTime的时间单位。
-
workQueue:存放待执行的任务的队列。
-
threadFactory:线程工厂
-
handler:拒绝策略,当核心线程—>队列—>最大线程数都达到最大值时。资源即达到设置的最大值,如新加入任务时,则根据handler的策略,进行后续处理。
2、源码学习
线程池使用例子:
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("file-upload-%d").build();
ExecutorService threadPool = new ThreadPoolExecutor(10, 20, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue(50), threadFactory, new ThreadPoolExecutor.AbortPolicy());
threadPool.execute(()->{
System.out.println("=======");
});
进入threadPool.execute()方法 分析ThreadPoolExecutor的execute方法
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
//running状态
int c = ctl.get();
//当前线程池,工作线程数小于核心线程数时,尝试添加新的工作线程
if (workerCountOf(c) < corePoolSize) {
//尝试添加工作线程,command为待执行的runnable,该参数为工作线程的first task,true为是否为核心线程
if (addWorker(command, true))
return;
c = ctl.get();
}
//尝试将新传入的任务添加到等待队列中
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
//检查线程池,是否shutdown,已被shutdown的线程池,则移除任务,并拒绝
if (! isRunning(recheck) && remove(command))
reject(command);
//如果线程池当前没有工作线程,则需要创建工作线程
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
//使用最大线程数尝试添加工作线程
else if (!addWorker(command, false))
//最终未获取到资源,则执行拒绝策略
reject(command);
}
进入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.
//如果状态大于SHUTDOWN 则不在添加新的工作线程。如果线程状态为SHUTDOWN,不能添加新核心线程,只可处理已经添加到执行队列内容
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
//如果为添加核心工作线程,判断是否大于核心线程。如果非核心线程,判断是否大于最大线程数 core(是否添加核心线程)
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
//cas添加running的状态的工作线程的数量
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;
}
进入工线程的执行方法:
new Worker(firstTask);
Worker继承Thread ,实际执行Worker的run()实现:
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
public void run() {
runWorker(this);
}
查看具体的实现: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 {
//firstTask不为空,或者队列获取不为空,工作线程一直执行任务
//所以线程当firstTask不为空,或者队列不为空且状态满足时,会一直存在
//分析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
//shutdownNow 方法执行时(stopping 状态),确保线程被终止
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.
//STOP 状态,或者SHUTDOWN状态且workQueue为空时,返回null,工作线程被回收
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
// Are workers subject to culling?
//回收的过程为线程大于核心线程,或者allowCoreThreadTimeOut 和timeout共同生效
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
//整体应该是:1:大于最大线程数的会被回收
//2.大于核心线程数的工作线程会被回收
//3.allowCoreThreadTimeOut设置为true,且 timedOut为true(队列里已无有效任务),核心工作线程回收
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}



