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. Python之爬虫(二十) Scrapy爬取所有知乎用户信息(上)

    爬取的思路 首先我们应该找到一个账号,这个账号被关注的人和关注的人都相对比较多的,就是下图中金字塔顶端的人,然后通过爬取这个账号的信息后,再爬取他关注的人和被关注的人的账号信息,然后爬取被关注人的账号 ...

  2. POJ 1095 Trees Made to Order 最详细的解题报告

    题目来源:Trees Made to Order 题目大意:根据下面的规则给一棵二叉树编号: 规则1:如果二叉树为空,则编号为0: 规则2:如果二叉树只有一个节点,则编号为1: 规则3:所有含有m个节 ...

  3. BFC 生成 特性 解决的问题

    BFC( 块级格式化上下文 ) 块级格式化上下文,它是指一个独立的块级渲染区域, 只有 Block­level BOX 参与,该区域拥有一套 渲染规则来约束块级盒子的布局,且与区域外部无关. 如何生成 ...

  4. ASP.NET Core策略授权和 ABP 授权

    目录 ASP.NET Core 中的策略授权 策略 定义一个 Controller 设定权限 定义策略 存储用户信息 标记访问权限 认证:Token 凭据 颁发登录凭据 自定义授权 IAuthoriz ...

  5. 微博大数据即席查询(OLAP)引擎实践

    前言 适用于 即席查询 场景的开源查询引擎有很多,如:Elasticsearch.Druid.Presto.ClickHouse等:每种系统各有利弊,有的擅长检索,有的擅长统计:实践证明,All In ...

  6. Java应用服务器之tomcat部署

    一.相关术语简介 首先我们来了解下tomcat是什么,tomcat是apache软件基金会中的一个项目,由apache.Sun 和其他一些公司及个人共同开发而成.主要作用是提供servlet和jsp类 ...

  7. easyUI时间控件

    ##=============================JSP======================================<div class="labelw l ...

  8. Python | Python初学者的自我修养,找到自己的方向

    本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是Python专题的第21篇文章,我们继续多线程的话题. 上周的文章当中我们简单介绍了线程和进程的概念,以及在Python当中如何在主线 ...

  9. 遍历map的6种方式

    1,平时开发中对map的使用很多,然后发现了很多map可能存在的各种问题:如HashMap 需要放置 1024 个元素,由于没有设置容量初始大小,随着元素不断增加,容量 7 次被迫扩大,resize ...

  10. spring学习(三)属性注入

    用的是IDEA的maven工程,pom.xml文件导包依赖省略 本文主要写set方式注入 (一).一般类型注入 一.写两个实体类Car.User public class Car { private ...