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. mysql子查询习题98

    #1.查询工资最低的员工信息:last name, salary SELECT last_name, salary FROM employees WHERE salary = ( SELECT MIN ...

  2. bzoj3620似乎在梦中见过的样子

    bzoj3620似乎在梦中见过的样子 题意: 给出一个字符串,要求求出形如A+B+A的子串数量,且lenA≥k,lenB≥1.字符串长度≤15000,k≤100,所以字符长度为小写字母. 题解: 第一 ...

  3. Ethical Hacking - GAINING ACCESS(9)

    Server Side Attack Nexpose - Analysing Scan Results and Generating Reports OS and Software Inforatio ...

  4. 用前端姿势玩docker【二】dockerfile定制镜像初体验

    前言 书接上文,关于dockerfile指令的api在此处不做赘述,在此只是记录下注意事项: '示坑以埋之'. 配置指令 FROM dockerfile必须以此开头 一个dockerfile可执行添加 ...

  5. Mock分页

    前后端分离开发时,一般会使用mock. 因为mock是用node运行的,行为与调用后台一致. 这样,不需要等后台写好,只要有接口文档,前端可以自己调接口,这样联调时遇到的问题会少很多,可以加快整体开发 ...

  6. Inoreader - 在线Rss阅读器

  7. Hadoop之HDFS常用文件操作命令

    命令基本格式:hadoop fs -cmd < args > 1. ls 列出hdfs文件系统根目录下的目录和文件hadoop fs -ls /dirhadoop fs -ls -R /d ...

  8. 一起学Blazor WebAssembly 开发(3)

    接着上篇,本篇开始讲下实现登录窗口,先看下大概的效果图: 打开的效果,没有美工美化 点登录校验得到不能为空 我在做blazor时用到了一个ui框架,这个框架名叫Ant Design blazor(ht ...

  9. socket链接

    服务端: package com.batch.service.impl; import java.io.BufferedReader; import java.io.BufferedWriter; i ...

  10. coding如何绑定二次验证码_虚拟MFA_两步验证_身份验证?

    Coding.net 是一个面向开发者的云端开发平台,提供 Git/SVN 代码托管.任务管理.在线 WebIDE.Cloud Studio.开发协作.文件管理.Wiki 管理.提供个人服务及企业管理 ...