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. 数据可视化之powerBI技巧(十四)采悟:PowerBI中自制中文单位万和亿

    使用PowerBI的时候,一个很不爽之处就是数据单位的设置,只能用千.百万等英美的习惯来显示,而没有我们中文所习惯的万亿等单位,虽然要求添加"万"的呼声很高,但迟迟未见到改进动作, ...

  2. 数据可视化之powerBI技巧(十三)PowerBI作图技巧:动态坐标轴

    之前的文章中介绍了如何制作动态的分析指标,这篇进行文章再介绍一下如何制作动态的坐标轴. 假设要分析的数据为销售额,分别从产品和地区两个维度进行分析,要实现的效果是,如果选择的是产品,则坐标轴是各个产品 ...

  3. Python函数05/内置函数/闭包

    Python函数05/内置函数/闭包 目录 Python函数05/内置函数/闭包 内容大纲 1.内置函数(二) 2.匿名函数及内置函数(重要) 3.闭包 4.今日总结 5.今日练习 内容大纲 1.内置 ...

  4. ATX学习(一)-atx-server

    今天无意中发现了ATX手机设备管理平台,瞬间勾引起了我极大的兴趣,这里对学习过程中的情况做个记录. 1.搭建环境 先按照作者步骤搭建环境出来吧,哇,突然发现ATX搭建环境很方便(一会就搭建好了)   ...

  5. CSS栅格布局

    CSS栅格布局 认识栅格布局 CSS的栅格布局也被称为网格布局(Grid Layout),它是一种新兴的布局方式. 栅格布局是一个二维系统,这意味着它可以同时处理列和行,与弹性布局相似,栅格系统也是由 ...

  6. echarts 踩坑 : id必须不同

    我们可能用react前端框架开发项目. 也就是组件化开发. 一个页面里可能有很多组件. 而echarts是寻找特定ID的DOM去渲染的. 也就是说,如果整个页面.包括所有页面组件,有id相同的DOM, ...

  7. 一款直击痛点的优秀http框架,让我超高效率完成了和第三方接口的对接

    1.背景 因为业务关系,要和许多不同第三方公司进行对接.这些服务商都提供基于http的api.但是每家公司提供api具体细节差别很大.有的基于RESTFUL规范,有的基于传统的http规范:有的需要在 ...

  8. xenomai内核解析---内核对象注册表—xnregistry(重要组件)

    1. 概述 上篇文章xenomai内核解析--同步互斥机制(一)--优先级倒置讲到,对于所有内核对象: xnregistry:保存内核对象,提供内核对象存储和快速检索. xnsynch:资源抽象,提供 ...

  9. 借鉴一个比较标准的后端RESTful API

    我们制定的 API 规范,使用了微服务架构所以做了一些改进,我们更偏向使用 http code 标识,不然需要自己处理成功或失败的逻辑,在 200 内再包一层显得啰嗦:并且微服务系列都不支持,Feig ...

  10. HTTP的实体数据

      数据类型表示实体数据的内容是什么,使用的是MIME    type,相关的头字段是Accept和Content-Type:  text:即文本格式的可读数据,我们最熟悉的应该就是text/html ...