Java线程池 ThreadPoolExecutor类
什么是线程池?
- java线程池是将大量的线程集中管理的类, 包括对线程的创建, 资源的管理, 线程生命周期的管理。
- 当系统中存在大量的异步任务的时候就考虑使用java线程池管理所有的线程, 从而减少系统资源的开销。
阿里的开发手册规范
- 线程池不允许使用 Executors 去创建,而是通过 ThreadPoolExecutor 的方式,这样 的处理方式让写的人更加明确线程池的运行规则,规避资源耗尽的风险。
- Executors 返回的线程池对象的弊端如下:
- FixedThreadPool 和 SingleThreadPool: 允许的请求队列长度为 Integer.MAX_VALUE,可能会堆积大量的请求,从而导致 OOM。
- CachedThreadPool 和 ScheduledThreadPool: 允许的创建线程数量为 Integer.MAX_VALUE,可能会创建大量的线程,从而导致 OOM。
线程池的创建
- new ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,long keepAliveTime, TimeUnit unit,BlockingQueue workQueue,RejectedExecutionHandler handler)
- corePoolSize: 线程池维护线程的最少数量
- maximumPoolSize: 线程池维护线程所允许的空闲时间
- unit: 线程池维护线程锁允许的空闲时间的单位
- workQueue: 线程池锁使用的缓冲队列
- handler: 线程池对拒绝任务的处理策略
添加任务到线程池
通过execute(Runnable) 方法添加到线程池, 任务就是一个Runnable类型的对象, 任务的执行方法就是Runnable类型对象的run()方法。
当一个任务通过execute(Runnable) 方法欲添加到线程池时:
- 如果此时线程池中线程的数量小于corePoolSize, 即使线程池中的线程都处于空闲状态,也要创建新的线程来处理被添加的任务。
- 如果此时线程池中的数量等于 corePoolSize,但是缓冲队列 workQueue未满,那么任务被放入缓冲队列
- 如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量小于maximumPoolSize,建新的线程来处理被添加的任务。
- 如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量等于maximumPoolSize,那么通过 handler所指定的策略来处理此任务。
也就是说:
- 处理任务的优先级为:
- 核心线程corePoolSize、任务队列workQueue、最大线程maximumPoolSize,如果三者都满了,使用handler处理被拒绝的任务。
- 处理任务的优先级为:
当线程池中的线程数量大于 corePoolSize时,如果某线程空闲时间超过keepAliveTime,线程将被终止。这样,线程池可以动态的调整池中的线程数。
unit可选的参数为java.util.concurrent.TimeUnit中的几个静态属性:NANOSECONDS、MICROSECONDS、MILLISECONDS、SECONDS。
workQueue常用的是:java.util.concurrent.ArrayBlockingQueue
handler的四个选择:
ThreadPoolExecutor.AbortPolicy() [直译过来流产计划?]
抛出 java.util.concurrent.RejectedExecutionException异常
/**
* A handler for rejected tasks that throws a
* {@code RejectedExecutionException}.
*/
public static class AbortPolicy implements RejectedExecutionHandler {
/**
* Creates an {@code AbortPolicy}.
*/
public AbortPolicy() { } /**
* Always throws RejectedExecutionException.
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
* @throws RejectedExecutionException always
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}
ThreadPoolExecutor.CallerRunsPolicy()
重试添加当前的任务,它会自动重复调用execute()方法
/**
* A handler for rejected tasks that runs the rejected task
* directly in the calling thread of the {@code execute} method,
* unless the executor has been shut down, in which case the task
* is discarded.
*/
public static class CallerRunsPolicy implements RejectedExecutionHandler {
/**
* Creates a {@code CallerRunsPolicy}.
*/
public CallerRunsPolicy() { } /**
* Executes task r in the caller's thread, unless the executor
* has been shut down, in which case the task is discarded.
* 在调用者的线程中执行任务r, 除非执行器被关闭, 任务才会被抛弃。
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
r.run();
}
}
}
ThreadPoolExecutor.DiscardOldestPolicy()
抛弃旧的任务
/**
* A handler for rejected tasks that discards the oldest unhandled
* request and then retries {@code execute}, unless the executor
* is shut down, in which case the task is discarded.
*/
public static class DiscardOldestPolicy implements RejectedExecutionHandler {
/**
* Creates a {@code DiscardOldestPolicy} for the given executor.
*/
public DiscardOldestPolicy() { } /**
* Obtains and ignores the next task that the executor
* would otherwise execute, if one is immediately available,
* and then retries execution of task r, unless the executor
* is shut down, in which case task r is instead discarded.
* 获取并忽视下一个执行器会执行的任务, 如果其中一个是当前可获取的, 并且
*多次重试执行过任务r。除非执行器被关闭, 任务才会被抛弃。
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
e.getQueue().poll();
e.execute(r);
}
}
}
}
ThreadPoolExecutor.DiscardPolicy()
抛弃当前的任务
/**
* A handler for rejected tasks that silently discards the
* rejected task.
*/
public static class DiscardPolicy implements RejectedExecutionHandler {
/**
* Creates a {@code DiscardPolicy}.
*/
public DiscardPolicy() { } /**
* Does nothing, which has the effect of discarding task r.
* 什么都不做, 就有抛弃任务r的效果
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
}
}
测试线程池Demo
package com.ronnie;
import java.io.Serializable;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolDemo {
private static int produceTaskSleepTime = 5;
private static int consumeTaskSleepTime = 5000;
private static int produceTaskMaxNumber = 20; // 定义最大添加20个线程到线程池中
/**
* 线程池执行的任务
*/
public static class ThreadPoolTask implements Runnable, Serializable{
private static final long serialVersionUID = 0;
// 保存任务所需要的数据
private Object threadPoolTaskData;
ThreadPoolTask(Object works){
this.threadPoolTaskData = works;
}
@Override
public void run() {
// 处理一个任务
System.out.println(threadPoolTaskData + "started......");
try {
// 便于观察, 等待一段时间
Thread.sleep(consumeTaskSleepTime);
} catch (Exception e){
e.printStackTrace();
}
threadPoolTaskData = null;
}
public Object getTask(){
return this.threadPoolTaskData;
}
}
public static void main(String[] args) {
// 构造一个线程池
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(6, 12, 9,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(6), new ThreadPoolExecutor.DiscardOldestPolicy());
for (int i = 1; i <= produceTaskMaxNumber; i++){
try {
// 创建一个任务并将其加入线程池
String work = "work@: " + i;
System.out.println("put: " + work);
threadPool.execute(new ThreadPoolTask(work));
// 等待一会儿, 便于观察
Thread.sleep(produceTaskSleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
执行结果
put: work@: 1
work@: 1started......
put: work@: 2
work@: 2started......
put: work@: 3
work@: 3started......
put: work@: 4
work@: 4started......
put: work@: 5
work@: 5started......
put: work@: 6
work@: 6started......
put: work@: 7
put: work@: 8
put: work@: 9
put: work@: 10
put: work@: 11
put: work@: 12
put: work@: 13
work@: 13started......
put: work@: 14
work@: 14started......
put: work@: 15
work@: 15started......
put: work@: 16
work@: 16started......
put: work@: 17
work@: 17started......
put: work@: 18
work@: 18started......
put: work@: 19
put: work@: 20
work@: 9started......
work@: 10started......
work@: 11started......
work@: 12started......
work@: 19started......
work@: 20started......
Java线程池 ThreadPoolExecutor类的更多相关文章
- Java线程池ThreadPoolExecutor类源码分析
前面我们在java线程池ThreadPoolExecutor类使用详解中对ThreadPoolExector线程池类的使用进行了详细阐述,这篇文章我们对其具体的源码进行一下分析和总结: 首先我们看下T ...
- java线程池ThreadPoolExecutor类使用详解
在<阿里巴巴java开发手册>中指出了线程资源必须通过线程池提供,不允许在应用中自行显示的创建线程,这样一方面是线程的创建更加规范,可以合理控制开辟线程的数量:另一方面线程的细节管理交给线 ...
- Java线程池ThreadPoolExecutor使用和分析(三) - 终止线程池原理
相关文章目录: Java线程池ThreadPoolExecutor使用和分析(一) Java线程池ThreadPoolExecutor使用和分析(二) - execute()原理 Java线程池Thr ...
- Java线程池ThreadPoolExecutor使用和分析(二) - execute()原理
相关文章目录: Java线程池ThreadPoolExecutor使用和分析(一) Java线程池ThreadPoolExecutor使用和分析(二) - execute()原理 Java线程池Thr ...
- Java线程池ThreadPoolExecutor使用和分析(一)
相关文章目录: Java线程池ThreadPoolExecutor使用和分析(一) Java线程池ThreadPoolExecutor使用和分析(二) - execute()原理 Java线程池Thr ...
- Java 线程池 ThreadPoolExecutor 的那些事儿
线程池基础知识 ThreadPoolExecutor : 一个线程池 Executors : 线程池工厂,通过该类可以取得一个拥有特定功能的线程池 ThreadPoolExecutor类实现了Exec ...
- 线程池 ThreadPoolExecutor 类的源码解析
线程池 ThreadPoolExecutor 类的源码解析: 1:数据结构的分析: private final BlockingQueue<Runnable> workQueue; // ...
- java线程池ThreadPoolExecutor使用简介
一.简介线程池类为 java.util.concurrent.ThreadPoolExecutor,常用构造方法为:ThreadPoolExecutor(int corePoolSize, int m ...
- 线程池ThreadPoolExecutor类的使用
1.使用线程池的好处? 第一:降低资源消耗.通过重复利用已创建的线程降低线程创建和销毁造成的消耗. 第二:提高响应速度.当任务到达时,任务可以不需要等到线程创建就能立即执行. 第三:提高线程的可管理性 ...
随机推荐
- crm系统和e_store商场的比较总结
e_store用了:Java.Servlet.JSP.Oracle.JQuery.Mybatis,tomcat技术 crm用了 :Java.JSP.Oracle.JQuery,Mybatis,spri ...
- 3_06_MSSQL课程_Ado.Net_接口、委托、事件、观察者模式
1.接口——实现接口 2.委托.事件(定义事件.注册事件.触发事件) 3.接口和事件的区别,怎么分情况用? 4.观察者模式作为设计模式的一种,也称发布订阅模式. 应对类型的变化和个数的变化. 中介设计 ...
- C语言程序编译
原来GCC的含义是GNU C Compiler,当初知识编译C语言,而现在GCC不知编译C语言,除此之外它还支持编译Ada.C++.Java.Object C.Pascal.COBOL.等等许多语言, ...
- C++打开文件夹
https://bbs.csdn.net/topics/392055617?page=1 见2楼 system("start \"\" \"文件夹路径\&q ...
- 关于hrf图的做法
要拿matlab 的spm 包功能做 Model specification ,review and estimation specify1st level 第二张图是在建模以后,通过spm中的res ...
- red hat 7、centos7的root密码破译
一.在开机画面时按"E". 二.找到linux16开头的这段,在段尾添加空格"rd.break"然后按Ctrl+x进入系统紧急救援模式. 三.新的界面出现命令行 ...
- Centos7 VNC远程桌面服务安装配置
1.服务器版本 CentOS Linux release 7.7.1908 (Core) 首先系统安装了GUI界面 # ln -sf /lib/systemd/system/graphical.tar ...
- Python学习笔记之基础篇(四)列表与元祖
#### 列表 li = ['alex','wusir','egon','女神','taibai'] ###增加的3种方法 ''' # append li.append('日天') li.append ...
- Hystrix熔断机制导致误报请求超时错误
问题的过程如下: (1)前端向服务端请求往HBase插入1000条数据: (2)请求经路由网关Zuul传递给HBaseService,HBaseService执行插入操作: (3)插入操作需要的时间超 ...
- [经验] Cocos Creator使用笔记 --- 调用不同脚本下的函数
因为 JavaScript 不同于 Java, 想要调用不同文件的函数的话不能直接 ClassName object = new ClassName(); object.function(param) ...