文章目录
前言
线程池是多线程编程中重要的工具,也是必会使用的技能。
一、啥是线程池?
线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。
二、作用?
- 当执行大量异步任务时线程池能够提供较好的性能
- 提供了一种资源限制和管理的手段,比如可以限制线程数,动态新增线程
二、使用步骤
1. 主要结构关系
其中关键的注意的是:
- ThreadPoolExcutor
- Worker
- RejectedExecutionHandler
2.Worker(打工人)
worker在线程池中主要的作用是执行任务,task.run()是他内部方法runWorker(Worker w)的一条执行语句,task就是任务对象 ,run就是执行体。先说这么多往下看
new Runnable() {
@Override
public void run() {
System.out.println("999999999");
}
}
//继承AbstractQueuedSynchronizer,实现接口 Runnable
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable
3.RejectedExecutionHandler(拒绝异常处理,拒绝策略,饱和策略)
- 就是在线程满了的情况下对新来任务的处理方法
- 4 个 策略(都是实现RejectedExcutorHandler接口,意味着你可以自定义策略setRejectedExecutionHandler(handler))
1、AbortPolicy : 默认策略,抛出异常( RejectedExecutionHandler defaultHandler = new AbortPolicy();)
2、CallerRunsPolicy :使用调用者所在线程执行任务
3、DiscardOldestPolicy :从阻塞队列丢弃一个任务,执行新任务
4、DiscardPolicy :默默丢弃,不抛出异常
2.ThreadPoolExcutor(主体)
先来创建一个案例
Executor executor = new ThreadPoolExecutor(2,//corePoolSize
10,//maximumPoolSize
60L,//keepAliveTime
TimeUnit.SECONDS,//timeUnit
new LinkedBlockingDeque<>(1));//workerQueue
executor1.execute(new Runnable() {//将任务放入线程池解析运行
@Override
public void run() {
System.out.println("999999999");
}
});
几个重要的参数
- corePoolSize(核心线程数):阻塞队列未满时存在的线程
- maximumPoolSize(最大线程池数):核心线程数 + 非核心线程数(阻塞队列满了后创建的线程)
- keepAliveTime(非核心线程的存活时间):(总线程数比核心线程多,且非核心线程闲置,允许非核心线程的存活时间)
- timeUnit(时间单位):存活时间的单位
- workerQueue(工作队列(阻塞队列)):保存等待任务的阻塞队列
几个重要的状态
- Running
- ShutDown
- Stop
- Tidying
- Terminated
上源码:
public void execute(Runnable command) {
/*
* 1、传入的对象为空,报NPE异常
* 2、如果总线程小于核心线程数 运行addWorker(command, true);
* 这里的true 是表示这个线程是核心线程,false的话则是非核心线程
* 3、如果第二步不满足则进行 if (isRunning(c) && workQueue.offer(command))判断
* 如果线程状态是Running且可以向阻塞队列未满,则将任务放入阻塞队列,内部又做了一次if
* 判断,如果状态更改且任务被删除了执行拒绝策略,如果总线程数是0的话,则创建一个非核心线程
* 如果添加失败的话,执行拒绝策略
*/
if (command == null)
throw new NullPointerException();
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);
}
下面我们来看下addWorker(command, true);方法,这段代码超长,需要一点耐心
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;
//将上面的判断条件改写为
//if (rs >= SHUTDOWN && (rs != shutdown || firstTask != null || workQueue.isEmpty()));
//rs > shutdown:线程池状态处于 STOP,TIDYING,TERMINATED时,添加工作线程失败,不接受新任务。 //rs >= shutdown && firstTask != null:线程池状态处于 SHUTDOWN,STOP,TIDYING,TERMINATED状态且worker的首个任务不为空时,添加工作线程失败,不接受新任务。
//rs >= shutdown && workQueue.isEmpty:线程池状态处于 SHUTDOWN,STOP,TIDYING,TERMINATED状态且阻塞队列为空时,添加工作线程失败,不接受新任务。
for (;;) {
int wc = workerCountOf(c);//获取线程池线程数量
if (wc >= CAPACITY || //线程数量超出返回false
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c)) //CAS增加线程数
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);//创建worker
/*Worker(Runnable firstTask) {
* setState(-1); // inhibit interrupts until runWorker
* this.firstTask = firstTask;
* this.thread = getThreadFactory().newThread(this);
*/}
final Thread t = w.thread; //将内部常量thread附赋给t
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();//给Workers加锁
try {
int rs = runStateOf(ctl.get());//当前线程状态
if (rs < SHUTDOWN || //状态是running 或者 状态是shutdown并且firstTask 为空,shutdown状态不接收新任务
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) // 如果t线程在运行,抛异常
throw new IllegalThreadStateException();
workers.add(w);//向workers中加入worker,workers是一个Hashset
int s = workers.size(); //得到worker数量
if (s > largestPoolSize)
largestPoolSize = s; //largestPoolSize的数值与worker数量保持一致
workerAdded = true; //标记添加成功
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
t.start(); //启动线程
workerStarted = true; //标记启动成功
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w); //添加失败
}
return workerStarted;
}
下面我们重新再来看Worker的执行方法runWorker(Worker w)
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();//获取当前线程
Runnable task = w.firstTask; // 将firstTask地址赋给task引用
w.firstTask = null; //将firstTask置为null
w.unlock(); // 允许被打断
boolean completedAbruptly = true;
try {
while (task != null || (task = getTask()) != null) {//task不为空
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) ||//线程池状态是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);//退出
}
}
总结
线程池添加任务流程图