ThreadPoolExecutor:JDK内置线程池实现

ThreadPoolTaskExecutor:Spring对JDK中线程池做了一层封装

参考代码:https://github.com/Noneplus/ConcurrentDemo

创建一个SpringBoot项目

主类开启异步注解

/**
* 开启异步注解@EnableAsync
*/
@SpringBootApplication
@EnableAsync
public class AsyncApplication { public static void main(String[] args) {
SpringApplication.run(AsyncApplication.class, args);
} }

创建线程池配置类

主类添加注解:@EnableConfigurationProperties({AsyncThreadPoolConfig.class} )

/**
* @Description: 线程池参数配置
* @Author noneplus
* @Date 2020/8/5 19:02
*/
@ConfigurationProperties("task.pool")
public class AsyncThreadPoolConfig{ private Integer corePoolSize; private Integer maxPoolSize; private Integer keepAliveSeconds; private Integer queueCapacity; public Integer getCorePoolSize() {
return corePoolSize;
} public void setCorePoolSize(Integer corePoolSize) {
this.corePoolSize = corePoolSize;
} public Integer getMaxPoolSize() {
return maxPoolSize;
} public void setMaxPoolSize(Integer maxPoolSize) {
this.maxPoolSize = maxPoolSize;
} public Integer getKeepAliveSeconds() {
return keepAliveSeconds;
} public void setKeepAliveSeconds(Integer keepAliveSeconds) {
this.keepAliveSeconds = keepAliveSeconds;
} public Integer getQueueCapacity() {
return queueCapacity;
} public void setQueueCapacity(Integer queueCapacity) {
this.queueCapacity = queueCapacity;
}
}

创建线程池实现类

继承AsyncConfigurer,重写get方法

package com.noneplus.async;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor; /**
* @Description: 重写Spring线程池
* @Author noneplus
* @Date 2020/8/6 10:11
*/
public class AsyncThreadPool implements AsyncConfigurer { @Autowired
AsyncThreadPoolConfig asyncThreadPoolConfig; /**
* ThreadPoolTaskExecutor 对比 ThreadPoolExecutor
* ThreadPoolExecutor:JDK内置线程池
* ThreadPoolTaskExecutor:Spring对ThreadPoolExecutor做了一层基础封装
*
* 相比 ThreadPoolExecutor,ThreadPoolTaskExecutor 增加了 submitListenable 方法,
* 该方法返回 ListenableFuture 接口对象,该接口完全抄袭了 google 的 guava。
* ListenableFuture 接口对象,增加了线程执行完毕后成功和失败的回调方法。
* 从而避免了 Future 需要以阻塞的方式调用 get,然后再执行成功和失败的方法。
*/
@Override
public Executor getAsyncExecutor() { ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); //设置核心线程数,最大线程数,队列容量,线程存活时间
threadPoolTaskExecutor.setCorePoolSize(asyncThreadPoolConfig.getCorePoolSize());
threadPoolTaskExecutor.setMaxPoolSize(asyncThreadPoolConfig.getMaxPoolSize());
threadPoolTaskExecutor.setQueueCapacity(asyncThreadPoolConfig.getQueueCapacity());
threadPoolTaskExecutor.setKeepAliveSeconds(asyncThreadPoolConfig.getKeepAliveSeconds()); //设置线程名前缀
threadPoolTaskExecutor.setThreadNamePrefix("AsyncThreadPool-"); // setRejectedExecutionHandler:当pool已经达到max size的时候,如何处理新任务
// CallerRunsPolicy:不在新线程中执行任务,而是由调用者所在的线程来执行
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 等待所有任务结束后再关闭线程池
threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
}

创建一个测试类Controller

定义一个forTest方法

/**
* @Description: TODO(这里用一句话描述这个类的作用)
* @Author noneplus
* @Date 2020/8/5 18:33
*/
@RestController
public class TestController { @Autowired
TestService testService; @GetMapping("/test")
public String forTest()
{
testService.forTest(); return "success";
}
}

创建异步Service方法

共三个线程,sendEmail,recoredLog和主线程

@Service
public class TestService { @Autowired
TaskComponent taskComponent; public void forTest() { taskComponent.sendEmail();
taskComponent.recordLog(); for (int i = 0; i < 10; i++) {
System.out.println("打酱油:" + i+"当前线程:"+Thread.currentThread().getName());
} }
}

定义异步的实现类

@Component
public class TaskComponent { @Async
public void sendEmail()
{
for (int i = 0; i < 10; i++) {
System.out.println("发送短信中:" + i+"当前线程:"+Thread.currentThread().getName());
}
} @Async
public void recordLog()
{
for (int i = 0; i < 10; i++) {
System.out.println("记录日志中:" + i+"当前线程:"+ Thread.currentThread().getName());
}
} }

重写ThreadPoolTaskExecutor的更多相关文章

  1. Spring的线程池ThreadPoolTaskExecutor使用案例

    1.Sping配置文件 <!-- 线程池配置 --> <bean id="threadPool" class="org.springframework. ...

  2. JAVA线程池学习,ThreadPoolTaskExecutor和ThreadPoolExecutor有何区别?

    初学者很容易看错,如果没有看到spring或者JUC源码的人肯定是不太了解的. ThreadPoolTaskExecutor是spring core包中的,而ThreadPoolExecutor是JD ...

  3. 线程池ThreadPoolTaskExecutor配置说明

    一般实际开发中经常用到多线程,所以需要使用线程池了, ThreadPoolTaskExecutor通常通过XML方式配置,或者通过Executors的工厂方法进行配置.  XML方式配置代码如下:交给 ...

  4. SPRING中的线程池ThreadPoolTaskExecutor(转)

    转自:https://blog.csdn.net/zhanglongfei_test/article/details/51888433 一.初始化 1,直接调用 ThreadPoolTaskExecu ...

  5. spring boot: 线程池ThreadPoolTaskExecutor, 多线程

    由于项目里需要用到线程池来提高处理速度,记录一下spring的taskExecutor执行器来实现线程池. ThreadPoolTaskExecutor的配置在网上找了很多解释没找到,看了下Threa ...

  6. ThreadPoolTaskExecutor使用详解(转)

    当并发或者异步操作,都会用到ThreadPoolTaskExecutor.现在对线程池稍作理解. /*** *@Auth dzb *@Date 22:29 2018/8/29 *@Descriptio ...

  7. ThreadPoolTaskExecutor使用详解

    当我们需要实现并发.异步等操作时,通常都会使用到ThreadPoolTaskExecutor,现对其使用稍作总结. 配置ThreadPoolTaskExecutor通常通过XML方式配置,或者通过Ex ...

  8. .NET 基础 一步步 一幕幕[面向对象之方法、方法的重载、方法的重写、方法的递归]

    方法.方法的重载.方法的重写.方法的递归 方法: 将一堆代码进行重用的一种机制. 语法: [访问修饰符] 返回类型 <方法名>(参数列表){ 方法主体: } 返回值类型:如果不需要写返回值 ...

  9. category中重写方法?

    问:可以在category中重写方法吗? 答:代码上可以实现 在category中重写方法,但在实际开发中,不建议这样做.如果确实需要重写原有方法也建议使用子类进行重写. category是为了更方便 ...

随机推荐

  1. Linux08 /Docker

    Linux08 /Docker 目录 Linux08 /Docker 1. docker简介/安装 2. Docker镜像加速器的设置 3. 核心三要素 镜像仓库/Registry 镜像/Image: ...

  2. python技巧 namedtuple

    python的namedtuple可以创建一个带字段名的元祖和一个带名字的类 In [1]: from collections import namedtuple ...: ...: nginx=na ...

  3. 基于animate.css动画库的全屏滚动小插件,适用于vue.js(移动端、pc)项目

    功能简介 基于animate.css动画库的全屏滚动,适用于vue.js(移动端.pc)项目. 安装 npm install vue-animate-fullpage --save 使用 main.j ...

  4. oracle终止用户会话

    1.创建两个测试用户进行实验 执行命令如下: create user test1 identified by 1; create user test2 identified by 1; grant d ...

  5. tk.mybatis selectByPrimaryKey无法正确识别主键

    selectByPrimaryKey无法正确识别主键,查看日志,发现报如下错误: ==> Preparing: SELECT username,password,name,age,sex,bir ...

  6. [jvm] -- 内存模型篇

    内存模型 JDK1.6  JDK1.8  线程私有的: 程序计数器 虚拟机栈 本地方法栈 线程共享的: 堆 方法区 直接内存 (非运行时数据区的一部分) 程序计数器 线程私有 两个作用 字节码解释器通 ...

  7. 题解 CF938G 【Shortest Path Queries】

    题目让我们维护一个连通无向图,边有边权,支持加边删边和询问从\(x\)到\(y\)的异或最短路. 考虑到有删边这样的撤销操作,那么用线段树分治来实现,用线段树来维护询问的时间轴. 将每一条边的出现时间 ...

  8. 按钮放到图片上,z-index和绝对定位

    说明: 最近在做一个banner轮播图 图的左下方有个 登录的按钮. 按钮死活都放不到图片上边,css太菜  特此记录一下 摆放下效果: 无论 轮播图怎么动 按钮不动 思路: 布局   banner轮 ...

  9. MySQL数据管理

    3.MySQL数据管理 3.1外键 方式一:  create table `grade`(  `gradeid` int(10) not null auto_increment comment '年纪 ...

  10. Java数组(基本+内存分析)

    一.数组概念   数组即为多个相同数据类型数据的数据按一定顺序排列的集合. 二.数组的特点   1.数组有数组名.索引.元素.素组长度:   2.数组的元素可以是基本数据类型也可以是引用数据类型:   ...