ThreadPoolExecutor原理和使用
大家先从ThreadPoolExecutor的整体流程入手:
针对ThreadPoolExecutor代码。我们来看下execute方法:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
//poolSize大于等于corePoolSize时不添加线程,反之新初始化线程
if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {
//线程运行状态外为运行,同一时候能够加入到队列中
if (runState == RUNNING && workQueue.offer(command)) {
if (runState != RUNNING || poolSize == 0)
ensureQueuedTaskHandled(command);
}
//poolSize大于等于corePoolSize时。新初始化线程
else if (!addIfUnderMaximumPoolSize(command))
//无法加入初始化运行线程,怎么运行reject操作(调用RejectedExecutionHandler)
reject(command); // is shutdown or saturated
}
}
我们再看下真正的线程运行者(Worker):
private final class Worker implements Runnable {
/**
* Runs a single task between before/after methods.
*/
private void runTask(Runnable task) {
final ReentrantLock runLock = this.runLock;
runLock.lock();
try {
/*
* If pool is stopping ensure thread is interrupted;
* if not, ensure thread is not interrupted. This requires
* a double-check of state in case the interrupt was
* cleared concurrently with a shutdownNow -- if so,
* the interrupt is re-enabled.
*/
//当线程池的运行状态为关闭等。则运行当前线程的interrupt()操作
if ((runState >= STOP ||
(Thread.interrupted() && runState >= STOP)) &&
hasRun)
thread.interrupt();
/*
* Track execution state to ensure that afterExecute
* is called only if task completed or threw
* exception. Otherwise, the caught runtime exception
* will have been thrown by afterExecute itself, in
* which case we don't want to call it again.
*/
boolean ran = false;
beforeExecute(thread, task);
try {
//任务运行
task.run();
ran = true;
afterExecute(task, null);
++completedTasks;
} catch (RuntimeException ex) {
if (!ran)
afterExecute(task, ex);
throw ex;
}
} finally {
runLock.unlock();
}
}
/**
* Main run loop
*/
public void run() {
try {
hasRun = true;
Runnable task = firstTask;
firstTask = null;
//推断是否存在须要运行的任务
while (task != null || (task = getTask()) != null) {
runTask(task);
task = null;
}
} finally {
//假设没有,则将工作线程移除,当poolSize为0是则尝试关闭线程池
workerDone(this);
}
}
}
/* Utilities for worker thread control */
/**
* Gets the next task for a worker thread to run. The general
* approach is similar to execute() in that worker threads trying
* to get a task to run do so on the basis of prevailing state
* accessed outside of locks. This may cause them to choose the
* "wrong" action, such as trying to exit because no tasks
* appear to be available, or entering a take when the pool is in
* the process of being shut down. These potential problems are
* countered by (1) rechecking pool state (in workerCanExit)
* before giving up, and (2) interrupting other workers upon
* shutdown, so they can recheck state. All other user-based state
* changes (to allowCoreThreadTimeOut etc) are OK even when
* performed asynchronously wrt getTask.
*
* @return the task
*/
Runnable getTask() {
for (;;) {
try {
int state = runState;
if (state > SHUTDOWN)
return null;
Runnable r;
if (state == SHUTDOWN) // Help drain queue
r = workQueue.poll();
//当线程池大于corePoolSize,同一时候,存在运行超时时间,则等待对应时间,拿出队列中的线程
else if (poolSize > corePoolSize || allowCoreThreadTimeOut)
r = workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS);
else
//堵塞等待队列中能够取到新线程
r = workQueue.take();
if (r != null)
return r;
//推断线程池运行状态。假设大于corePoolSize,或者线程队列为空,也或者线程池为终止的工作线程能够销毁
if (workerCanExit()) {
if (runState >= SHUTDOWN) // Wake up others
interruptIdleWorkers();
return null;
}
// Else retry
} catch (InterruptedException ie) {
// On interruption, re-check runState
}
}
}
/**
* Performs bookkeeping for an exiting worker thread.
* @param w the worker
*/
//记录运行任务数量,将工作线程移除。当poolSize为0是则尝试关闭线程池
void workerDone(Worker w) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
completedTaskCount += w.completedTasks;
workers.remove(w);
if (--poolSize == 0)
tryTerminate();
} finally {
mainLock.unlock();
}
}
通过上述代码,总结下四个keyword的使用方法
- corePoolSize 核心线程数量
线程保有量,线程池总永久保存运行线程的数量
- maximumPoolSize 最大线程数量
最大线程量,线程最多不能超过此属性设置的数量,当大于线程保有量后,会新启动线程来满足线程运行。
- 线程存活时间
获取队列中任务的超时时间。当阈值时间内无法获取线程,则会销毁处理线程,前提是线程数量在corePoolSize 以上
- 运行队列
运行队列是针对任务的缓存,任务在提交至线程池时。都会压入到运行队列中。所以这里大家最好设置下队列的上限。防止溢出
ThreadPoolExecuter的几种实现
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
- CachedThreadPool 运行线程不固定,
优点:能够把新增任务所有缓存在一起,
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
- 单线程线程池
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}
- 固定长度线程池
版权声明:本文博客原创文章。博客,未经同意,不得转载。
ThreadPoolExecutor原理和使用的更多相关文章
- Java线程池ThreadPoolExecutor原理和用法
1.ThreadPoolExecutor构造方法 public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAli ...
- Java 线程池(ThreadPoolExecutor)原理分析与使用
在我们的开发中"池"的概念并不罕见,有数据库连接池.线程池.对象池.常量池等等.下面我们主要针对线程池来一步一步揭开线程池的面纱. 使用线程池的好处 1.降低资源消耗 可以重复利用 ...
- Java 线程池(ThreadPoolExecutor)原理解析
在我们的开发中“池”的概念并不罕见,有数据库连接池.线程池.对象池.常量池等等.下面我们主要针对线程池来一步一步揭开线程池的面纱. 有关java线程技术文章还可以推荐阅读:<关于java多线程w ...
- Java线程池(ThreadPoolExecutor)原理分析与使用
在我们的开发中"池"的概念并不罕见,有数据库连接池.线程池.对象池.常量池等等.下面我们主要针对线程池来一步一步揭开线程池的面纱. 使用线程池的好处 1.降低资源消耗 可以重复利用 ...
- Java - "JUC线程池" ThreadPoolExecutor原理解析
Java多线程系列--“JUC线程池”02之 线程池原理(一) ThreadPoolExecutor简介 ThreadPoolExecutor是线程池类.对于线程池,可以通俗的将它理解为"存 ...
- Java并发包中线程池ThreadPoolExecutor原理探究
一.线程池简介 线程池的使用主要是解决两个问题:①当执行大量异步任务的时候线程池能够提供更好的性能,在不使用线程池时候,每当需要执行异步任务的时候直接new一个线程来运行的话,线程的创建和销毁都是需要 ...
- 简单看看ThreadPoolExecutor原理
线程池的作用就不多说了,其实就是解决两类问题:一是当执行大量的异步任务时线程池能够提供较好的性能,在不使用线程池时,每当需要执行异步任务是需要直接new一个线程去执行,而线程的创建和销毁是需要花销的, ...
- Java入门系列之线程池ThreadPoolExecutor原理分析思考(十五)
前言 关于线程池原理分析请参看<http://objcoding.com/2019/04/25/threadpool-running/>,建议对原理不太了解的童鞋先看下此文然后再来看本文, ...
- Java 线程池(ThreadPoolExecutor)原理分析与实际运用
在我们的开发中"池"的概念并不罕见,有数据库连接池.线程池.对象池.常量池等等.下面我们主要针对线程池来一步一步揭开线程池的面纱. 有关java线程技术文章还可以推荐阅读:< ...
- 线程池 ThreadPoolExecutor 原理及源码笔记
前言 前面在学习 JUC 源码时,很多代码举例中都使用了线程池 ThreadPoolExecutor,并且在工作中也经常用到线程池,所以现在就一步一步看看,线程池的源码,了解其背后的核心原理. 公众号 ...
随机推荐
- 使用ionic3快速开发webapp(二)
本文整理了使用ionic3开发时会用到的一些最基本组件及用法 1.ion-tabs 最常见的通过标签切换页面: tabs.html <ion-tabs> <ion-tab [root ...
- P2P网络借贷系统-核心功能-用户投标-业务讲解
用户投标是P2P网络借贷系统的核心功能,相对比较复杂,为了更好地梳理业务和技术实现思路,特地详细总结分析下. 输入:用户id-uid,标的id-lid,投标金额-amount 1.根据lid,获得贷款 ...
- jquery 多选框 checkbox 获取选中的框
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- mac nginx php-fpm
再一次被困在一个傻问题.由于我居然怀疑是不是mac本身就和centos的安装不一样.在一次次地排错后,最终发现.原来是我的nginx.conf的一行配置少写了一个字母.最后多亏用ls检查来定位到这个错 ...
- asp.net中,<%#%>,<%=%>和<%%>各自是什么意思,有什么差别
在asp.net中经常出现包括这样的形式<%%>的html代码,总的来说包括以下这样几种格式: 一. <%%> 这样的格式实际上就是和asp的使用方法一样的,仅仅是asp中里面 ...
- Android 设置alpha值来制作透明与渐变效果的实例
Android系统支持的颜色是由4个值组成的,前3个为RGB,也就是我们常说的三原色(红.绿.蓝),最后一个值是A,也就是Alpha.这4个值都在0~255之间.颜色值越小,表示该颜色越淡,颜色值越大 ...
- 2015年创业中遇到的技术问题:1-10(乱码-SpringMVC-jquery-JSON等)
1.数据库表名重构. 之前受PHP等程序的影响,数据库表名喜欢用数据库的名称作为前缀,比如"p2p_account". 在经过大量的实践之后,发现Java程序中,基本没 ...
- Popup 解决位置不随窗口/元素FrameworkElement 移动更新的问题
原文:Popup 解决位置不随窗口/元素FrameworkElement 移动更新的问题 Popup弹出后,因业务需求设置了StaysOpen=true后,移动窗口位置或者改变窗口大小,Popup的位 ...
- Oracle数据库表空间 数据文件 用户 以及表创建的SQL代码
--create the tablespace CREATE SMALLFILE TABLESPACE "TABLE_CONTAINER" --创建表空间 DATAFILE 'E: ...
- python request get
import requests from urllib import parse # 返回response resp = requests.get("https://www.baidu.co ...