并发编程(3)——ThreadPoolExecutor
ThreadPoolExecutor
1. ctl(control state)
线程池控制状态,包含两个概念字段:workerCount(线程有效数量)和runState(表示是否在运行、关闭等状态)
workerCount限制到2^29 - 1 (5亿左右)
runstate有如下几个状态:
RUNNING: 接收新任务,并处理队列中的任务
SHUTDOWN: 不接收新任务,但处理队列中的任务
STOP: 不接收新任务,也不处理队列中任务,并且会中断运行中的任务
TIDYING: 所有任务都被终止,workerCount是0,过渡到TIDYING状态的线程会执行terminated()钩子方法
TERMINATED:terminated()方法执行完毕
几种常量:
RUNNING=-1<<29=-536870912,
SHUTDOWN=0 << 29=0,
STOP = 1 << 29=536870912,
TIDYING = 2 << 29=1073741824,
TERMINATED = 3 << 29 = 1610612736.
ctl初始值=RUNNING | 0 = -1 << 29=-536870912.
2. 构造器:
public ThreadPoolExecutor( int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
corePoolSize: 线程池中保留的线程数量
maximumPoolSize: 线程池允许的最大线程数量
keepAliveTime:当线程池中数量大于corePoolSize,这是多余的空闲线程等待新任务的最大时间,超过则terminate
uinit: keepAliveTime的时间单位,通常是TimeUnit里的
workQueue: 队列
threadFactory: 主要用来给线程起名字,默认前缀"pool-" + poolNumber.getAndIncrement() + "-thread-";
handler: 拒绝策略。分四种:
DiscardOldestPolicy,丢弃最老的未处理请求,然后尝试执行
AbortPolicy, 直接丢弃(默认)
CallerRunsPolicy,在调用线程里的execute方法里执行拒绝的任务
DiscardPolicy: 悄悄的丢弃拒绝的任务。
3. execute方法
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) { // 判断workerCount是否达到了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实现:
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {// 1. 自旋过程主要进行一些校验,最主要的是增加wc
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
/** 这一部分参考各个状态的处理策略,rs>=shutdown的,不再接收新任务,分为三种情况
* 1. rs是stop,tidying,terminated状态
* 2. rs是shutdown,但firstTask != null
* 3. rs是shutdown,workQueue队列为空
* 符合这三种,则return false
*/
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
}
}
// 下面这段启动worker
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
// 注意:private final class Worker extends AbstractQueuedSynchronizer implements Runnable
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;
}
t.start调用Worker的run方法,接着调用runWorker方法:
4. shutdown vs shutdownNow
shutdown:
主要两步:
- advanceRunState(SHUTDOWN);设置状态为SHUTDOWN
- interruptIdleWorkers();中断所有未在执行任务的线程
这里,第二步判断如下:
if (!t.isInterrupted() && w.tryLock()) {
try {
t.interrupt();
} catch (SecurityException ignore) {
} finally {
w.unlock();
}
}
w.tryLock(),正如javadoc所说,因为Worker创建之后会运行,运行的时候runWorker(this)方法会获取锁,只有不在运行的任务才可以获取到锁。
* Interrupts threads that might be waiting for tasks (as
* indicated by not being locked) so they can check for
* termination or configuration changes
shutdownNow()方法
- advanceRunState(STOP);设置状态为STOP
- interruptWorkers(); 中断所有线程
- tasks = drainQueue(); 返回等待执行任务的列表
5. Worker
类定义:
private final class Worker extends AbstractQueuedSynchronizer implements Runnable
成员变量: Thread thread——worker运行所在的线程
Runnable firstTask——初始运行任务,有可能是null.
其中的lock(),tryLock(),unlock(),tryAcquire(),tryRelease()等方法是AQS中的常用方法,这里暂且略过。
看一下Worker的run方法:
public void run() { 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 {
// 运行完worker的初始任务firstTask之后,从workQueue中获取任务,直到任务为空
while (task != null || (task = getTask()) != null) {
w.lock();
/**
* 中断的一些判断,1. 线程池STOP状态并且当前线程未中断需要中断
* 2. Thread.interrupted()[In other words, if this method were to be called twice in succession, the second call would return false]换句话讲,如果在shutdownNow方法中线程被中断,则interrupted状态应该为true。額,这里也没搞懂为什么要调用Thread.interrupted()来清除interrupted状态。
*/
// 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 {
// 和after一样是钩子方法hook
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);
}
}
6. 其他
- allowCoreThreadTimeOut, 默认false,核心线程即使空闲下来也会保证存活,如果是true的话,核心线程使用keepAliveTime超时时间。
- mainLock, 保持workers稳定,文件中获取锁都是通过mainLock.lock()来实现的。
- workers: 包含线程池中所有worker线程的Set。只有持有mainLock的锁,才可以访问。
- termination: 支持awaitTermination()的wait 条件,是Condition的实现AQS中的ConditionObject。
- runnable转Callable: Executors.callable(runnable, result)这里用了适配器RunnableAdapter
- ThreadPoolExecutor的submit参数无论是Runnable还是Callable,都是先转成RunnableFuture,再调用execute(Runnable runnable)方法。
Executors
常用的几种方法:
固定线程数的线程池
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService(
new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
}
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
BlockingQueue
add(E e): 没有违反容量限制的话,插入成功返回true,如果没有位置插入的话,抛出IlleagalStateException。
offer(E e):没有违反容量限制的话,插入成功返回true,如果没有位置插入的话,返回false。当使用capacity-restricted队列时,优于add方法。
put (E e): 有空间的时候再进行插入。
take: 获取并删除队列头结点,阻塞直到有节点可用。
poll: Retrieves and removes the head of this queue, waiting up to the
* specified wait time if necessary for an element to become available.
remove: 删除队列中的某个元素。
常见的一些实现:
- ArrayBlockingQueue
- SynchronousQueue
- DelayQueue
- PriorityBlockingQueue
并发编程(3)——ThreadPoolExecutor的更多相关文章
- Java并发编程:ThreadPoolExecutor + Callable + Future(FutureTask) 探知线程的执行状况
如题 (总结要点) 使用ThreadPoolExecutor来创建线程,使用Callable + Future 来执行并探知线程执行情况: V get (long timeout, TimeUnit ...
- 【并发编程】ThreadPoolExecutor参数详解
ThreadPoolExecutor executor = new ThreadPoolExecutor( int corePoolSize, int maximumPoolSize, long ke ...
- 【并发编程】- ThreadPoolExecutor篇
Executor框架 Executor框架的两级调度模型(基于HotSpot) 在上层,Java多线程程序通常把应用分解为若干个任务,然后使用用户级的调度器(Executor框架)将这些任务映射为固定 ...
- 并发编程 13—— 线程池的使用 之 配置ThreadPoolExecutor 和 饱和策略
Java并发编程实践 目录 并发编程 01—— ThreadLocal 并发编程 02—— ConcurrentHashMap 并发编程 03—— 阻塞队列和生产者-消费者模式 并发编程 04—— 闭 ...
- Java并发编程:Java线程池核心ThreadPoolExecutor的使用和原理分析
目录 引出线程池 Executor框架 ThreadPoolExecutor详解 构造函数 重要的变量 线程池执行流程 任务队列workQueue 任务拒绝策略 线程池的关闭 ThreadPoolEx ...
- 并发编程学习笔记(14)----ThreadPoolExecutor(线程池)的使用及原理
1. 概述 1.1 什么是线程池 与jdbc连接池类似,在创建线程池或销毁线程时,会消耗大量的系统资源,因此在java中提出了线程池的概念,预先创建好固定数量的线程,当有任务需要线程去执行时,不用再去 ...
- java并发编程(十七)Executor框架和线程池
转载请注明出处:http://blog.csdn.net/ns_code/article/details/17465497 Executor框架简介 在Java 5之后,并发编程引入了一堆新的启动 ...
- Java并发编程:线程池的使用
Java并发编程:线程池的使用 在前面的文章中,我们使用线程的时候就去创建一个线程,这样实现起来非常简便,但是就会有一个问题: 如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了, ...
- 并发编程 01—— ThreadLocal
Java并发编程实践 目录 并发编程 01—— ThreadLocal 并发编程 02—— ConcurrentHashMap 并发编程 03—— 阻塞队列和生产者-消费者模式 并发编程 04—— 闭 ...
- 并发编程 20—— AbstractQueuedSynchronizer 深入分析
Java并发编程实践 目录 并发编程 01—— ThreadLocal 并发编程 02—— ConcurrentHashMap 并发编程 03—— 阻塞队列和生产者-消费者模式 并发编程 04—— 闭 ...
随机推荐
- 牛逼哄哄的Qt库
目录 一.有价值 - 好的网站 - 好的文章 二.Qt开源库-工具 - QtXlsx--excel读写库 三.Qt开源库-控件 - libqxt编译 - Qwt - QCustomPlot - 其他 ...
- Python与C/C++相互调用
参考链接:https://www.cnblogs.com/yanzi-meng/p/8066944.html
- C# 中奇妙的函数–6. 五个序列聚合运算(Sum, Average, Min, Max,Aggregate)
今天,我们将着眼于五个用于序列的聚合运算.很多时候当我们在对序列进行操作时,我们想要做基于这些序列执行某种汇总然后,计算结果. Enumerable 静态类的LINQ扩展方法可以做到这一点 .就像之前 ...
- 深入理解Java的switch...case...语句
switch...case...中条件表达式的演进 最早时,只支持int.char.byte.short这样的整型的基本类型或对应的包装类型Integer.Character.Byte.Short常量 ...
- Bzoj 4582 [Usaco2016 Open] Diamond Collector 题解
4582: [Usaco2016 Open]Diamond Collector Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 204 Solved: ...
- 使用gets函数常见问题
C语言面试经常会考如下一道题,哪里有错误: #include <stdio.h> int main() { char string[100] = {'\0'}; ...
- LINUX安装源码软件经典三部曲
这几天一直在搞suse下的mplyaer.ffmpeg等源码编译安装,总结出源码软件安装三部曲,网上称为经典三部曲. 这三步分别为: 1. ./configure [options] 2. make ...
- Spring Cloud使用Zuul网关时报错
当开启了Eureka集群后,每创建一个服务都要往这两个集群中进行注册否则访问时会产生500
- 关于Linux服务器配置java环境遇到的问题
关于Linux服务器配置java环境遇到的问题 将下载好的JDK安装包解压到/etc/local/路径下,安装完后用vim/etc/profile文件,在文件末尾添加 export JAVA_HOME ...
- 【最小生成树之Prim算法】-C++
[最小生成树之Kruskal算法] 没有看过的可以先看↑,会更简单. [模板]最小生成树 这一篇博客主要是介绍另外一种算法:Prim算法. prim算法就好像是一棵"生成树"在慢慢 ...