线程池。线程池是什么,说究竟,线程池是处理多线程的一种形式,管理线程的创建,任务的运行,避免了无限创建新的线程带来的资源消耗,可以提高应用的性能。非常多相关操作都是离不开的线程池的,比方android应用中网络请求的封装。这篇博客要解决的问题是:

1.线程池的工作原理及过程。

要分析线程池的工作原理及过程,还是要从它的源代码实现入手,首先是线程是构造方法,何谓构造方法。构造方法就是对成员变量进行初始化,在这里,我们能够看到它的构造方法:

/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
* @param unit the time unit for the {@code keepAliveTime} argument
* @param workQueue the queue to use for holding tasks before they are
* executed. This queue will hold only the {@code Runnable}
* tasks submitted by the {@code execute} method.
* @param threadFactory the factory to use when the executor
* creates a new thread
* @param handler the handler to use when execution is blocked
* because the thread bounds and queue capacities are reached
* @throws IllegalArgumentException if one of the following holds:<br>
* {@code corePoolSize < 0}<br>
* {@code keepAliveTime < 0}<br>
* {@code maximumPoolSize <= 0}<br>
* {@code maximumPoolSize < corePoolSize}
* @throws NullPointerException if {@code workQueue}
* or {@code threadFactory} or {@code handler} is null
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> 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核心线程的数量;maximumPoolSize最大线程数量。keepAliveTime和 TimeUnit非核心线程闲置时间,超过这个设置时间将会被终止,TimeUnit含有多种静态成员变量作为单位,如seconds;BlockingQueue任务堵塞队列,当核心线程创建数量达到最大值时,任务首先会加入到堵塞队列。等待运行;ThreadFactory 线程构造工厂。经常使用的有DefaultThreadFactory,我们也能够重写它的newThread方法,实现这个类;RejectedExecutionHandler,当任务被拒绝加入时。将会交给这个类处理。好了,构造的过程。就是这么简单,就是初始化一些成员变量。

分析的时候。从关键点着手,这里分析是从execute()方法入手的:

 /**
* Executes the given task sometime in the future. The task
* may execute in a new thread or in an existing pooled thread.
*
* If the task cannot be submitted for execution, either because this
* executor has been shutdown or because its capacity has been reached,
* the task is handled by the current {@code RejectedExecutionHandler}.
*
* @param command the task to execute
* @throws RejectedExecutionException at discretion of
* {@code RejectedExecutionHandler}, if the task
* cannot be accepted for execution
* @throws NullPointerException if {@code command} is null
*/
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();
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);
}

上面execute的方法,传入的是一个Runnable,这种方法就是我们须要运行的任务。以下我们分析execute是怎么运行这个任务的,也就是execute运行的过程:

1.假设线程池中线程的数量小于核心线程数目,则启动一个新的线程处理这个任务。

2.假设核心线程处于非空暇状态,则将任务插入到堵塞队列中,当有线程空暇时,会自己主动取出任务运行。

3.假设堵塞队列任务已经满了。而且当前线程小于最大线程数目,则启动新的线程。运行任务。假设超过了最大线程数,则拒绝接受新的任务。

上面是整个代码的过程,如今我们队代码进行分析

 if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;

workerCountOf(c)表示的是当前线程的数量。假设这个数量小于corePoolSize,则调用addWorker(command,true)方法,假设addWorker运行成功,返回true,表示任务运行完毕。以下我们看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);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
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;
}

addWorker方法比較长,我们分为两块,第一块的for循环,第二块try...。第一块,for循环。主要是推断当前能否够运行任务,假设能够,则进行以下的try,通过的条件。能够分析出来。是当前线程小于核心线程。或者当前堵塞队列已满,线程数小于最大线程数量。满足这两个中的条件,才干往下走。       try里面通过当前的參数,新建了一个Worker,这个Worker实现了Runable接口,Worker里面通过ThreadFactory构建了一个Thread来运行这个任务,代码的后面,调用了t.start(),实际上,调用的是,Worker实现Runable的run方法。run方法调用的又是runWorker(),我们看runWorker方法

 final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
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);
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);
}
}

首先我们要知道,整个runWorker方法是在Thread的线程中运行的。runWorker中,while循环中,加锁,第一次task不为空,运行这个firstTask,当task.run()运行完,解锁,然后调用getTask()。getTask是从堵塞队列中取出任务来运行,因此,这里,我们得出结论。当线程完毕一个任务时。会从堵塞队列里取出任务来运行。        while循环的条件是,task 不为空。或者getTask不为空,假设task为空。而且getTask也为空,就跳出循环,可是,先请看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? boolean timed = allowCoreThreadTimeOut || wc > corePoolSize; 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;
}
}
}

这种方法的主要作用是从队列中取出一个任务运行,然而。我们细致分析。假设allowCoreThreadTimeOut为true(也就是说同意核心线程超时),或者当前线程是非核心线程,那么timed=true,这时候。进入if语句推断,wc>maximuPoolsize,这个一般不成立。直接看timed&&timeOut,timed=true,timeOut为false,直接进入try,最后timeOut=true,当后面循环时,假设队列的任务为空,就会运行到compareAndDecrementWorkerCount(c)降低一个线程数量,然后返回null,线程也就终止运行了;可是假设allowCoreThreadTimeOut=false,就会直接调用workQueue.take(),直接取出一个Runnable。假设runnable为空,就将一直循环,线程堵塞在这里,也就是核心线程处于空暇状态。

这里得出新的结论。假设核心线程没有同意超时。那么它将一直处于空暇状态,不会被回收。

我们再次回到execute方法。第二部分

 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);
}

假设当前线程池处于执行状态,而且这个任务能插入到队列中(由于这里线程数目已经时等于核心线程数了。因此插入到队列中,等待执行)。第二次推断。假设当前线程池不处于执行状态。那么移除这个任务,调用reject方法处理;假设当前线程池的线程数量为0,addWorker(),传入null和false,也就是说,不加入新任务,而且时启动一个非核心线程,这个核心线程会通过getTask()方法取出任务执行。这个和上面分析的过程一样。

第三部分

 else if (!addWorker(command, false))
reject(command);

先启动一个非核心线程运行任务。假设非核心线程达到了最大线程数,才会拒绝运行任务。

最后的结论就是:

1.假设线程池中线程的数量小于核心线程数目,则启动一个新的线程处理这个任务。

2.假设核心线程处于非空暇状态,则将任务插入到堵塞队列中。当有线程空暇时,会自己主动取出任务运行。

3.假设堵塞队列任务已经满了,而且当前线程小于最大线程数目,则启动新的线程。运行任务,假设超过了最大线程数,则拒绝接受新的任务。

假设核心线程没有设置为同意超时。那么核心线程会一直存在,即时等待运行任务。

线程池ThreadPoolExecutor分析的更多相关文章

  1. 线程池ThreadPoolExecutor分析: 线程池是什么时候创建线程的,队列中的任务是什么时候取出来的?

    带着几个问题进入源码分析: 1. 线程池是什么时候创建线程的? 2. 任务runnable task是先放到core到maxThread之间的线程,还是先放到队列? 3. 队列中的任务是什么时候取出来 ...

  2. [转]ThreadPoolExecutor线程池的分析和使用

    1. 引言 合理利用线程池能够带来三个好处. 第一:降低资源消耗.通过重复利用已创建的线程降低线程创建和销毁造成的消耗. 第二:提高响应速度.当任务到达时,任务可以不需要等到线程创建就能立即执行. 第 ...

  3. Java线程池ThreadPoolExecutor使用和分析(三) - 终止线程池原理

    相关文章目录: Java线程池ThreadPoolExecutor使用和分析(一) Java线程池ThreadPoolExecutor使用和分析(二) - execute()原理 Java线程池Thr ...

  4. Java线程池ThreadPoolExecutor使用和分析(二) - execute()原理

    相关文章目录: Java线程池ThreadPoolExecutor使用和分析(一) Java线程池ThreadPoolExecutor使用和分析(二) - execute()原理 Java线程池Thr ...

  5. Java线程池ThreadPoolExecutor使用和分析(一)

    相关文章目录: Java线程池ThreadPoolExecutor使用和分析(一) Java线程池ThreadPoolExecutor使用和分析(二) - execute()原理 Java线程池Thr ...

  6. ThreadPoolExecutor线程池的分析和使用

    1. 引言 合理利用线程池能够带来三个好处. 第一:降低资源消耗.通过重复利用已创建的线程降低线程创建和销毁造成的消耗. 第二:提高响应速度.当任务到达时,任务可以不需要等到线程创建就能立即执行. 第 ...

  7. 多线程学习笔记八之线程池ThreadPoolExecutor实现分析

    目录 简介 继承结构 实现分析 ThreadPoolExecutor类属性 线程池状态 构造方法 execute(Runnable command) addWorker(Runnable firstT ...

  8. Java线程池ThreadPoolExecutor类源码分析

    前面我们在java线程池ThreadPoolExecutor类使用详解中对ThreadPoolExector线程池类的使用进行了详细阐述,这篇文章我们对其具体的源码进行一下分析和总结: 首先我们看下T ...

  9. Java入门系列之线程池ThreadPoolExecutor原理分析思考(十五)

    前言 关于线程池原理分析请参看<http://objcoding.com/2019/04/25/threadpool-running/>,建议对原理不太了解的童鞋先看下此文然后再来看本文, ...

随机推荐

  1. LA 4256 DP Salesmen

    d(i, j)表示使前i个数满足要求,而且第i个数值为j的最小改动次数. d(i, j) = min{ d(i-1, k) | k == j | G[j][k] } #include <cstd ...

  2. js request学习

    SP的内置对象在JSP页面中无须声明就可以直接使用,其内置对象常用的有Request,response,session,application,out,config,pageCOntext reque ...

  3. goland 快键键整理及注册

    https://my.oschina.net/lemos/blog/1358731 http://idea.lanyus.com/

  4. SQL Server on Red Hat Enterprise Linux

    本文从零开始一步一步介绍如何在Red Hat Enterprise Linux上搭建SQL Server 2017,包括安装系统.安装SQL等相关步骤和方法(仅供测试学习之用,基础篇). 一.   创 ...

  5. 大数据学习——azkaban工作流调度系统

    azkaban的安装部署 在/root/apps 1目录下新建azkaban文件夹 上传安装包到azkaban 2解压 .tar.gz 3删掉安装包 [root@mini1 azkaban]# .ta ...

  6. 【C#】穿马甲的流程控制语句

    导读:话说当年选择.顺序.循环语句风靡整个VB,今年发现,那几个东西又换了件衣服,跑到了C#里蹦跶.开始,真被这几个穿马甲的吓了一跳,没看出来这是老伙伴.突然有一天,瞥见了脱下新衣的孩子们.哈哈哈哈. ...

  7. 九度oj 题目1048:判断三角形类型

    题目描述: 给定三角形的三条边,a,b,c.判断该三角形类型. 输入: 测试数据有多组,每组输入三角形的三条边. 输出: 对于每组输入,输出直角三角形.锐角三角形.或是钝角三角形. 样例输入: 3 4 ...

  8. Python脚本实现单据体首行过滤

    编写的Python脚本 可以看到,实际代码只有3句,即实现单据体首行过滤代码(其实最最主要的是无需写组件动态即时注册),并有注册到[采购订单]"表单构建插件"上.界面运行时,实际效 ...

  9. Java 模板权重随机

    Template templates=...// 所有的模板 final int _weights=1000; // 所有的模板权重 Template _template=null; //随机一个权重 ...

  10. Delphi中Indy 10的安装和老版本的卸载

    http://www.cnblogs.com/railgunman/archive/2010/08/31/1814112.html Indy 10的安装和老版本的卸载 Indy 10下载地址: htt ...