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());
}
} }

最新文章

  1. JAVA spring hibernate 多数据源配置记录
  2. lvs源代码分析
  3. 为什么xcode7请求不成功
  4. Android-Universal-Image-Loader开源项目的简要说明及使用实例
  5. 45. Jump Game II
  6. 8天学通MongoDB——第五天 主从复制
  7. js获取客户端IP及地理位置
  8. 本地搜索神器-Everything
  9. 安卓高手之路之 ClassLoader
  10. SQLite学习第02天:数据类型
  11. centos7 jsoup java.net.UnknownHostException
  12. linux下的java远程调试jpda+tomcat
  13. Spring MVC Controller 单元测试
  14. ABP Zero 单部署,单数据库,多租户架构
  15. win8系统不小心禁用了管理员权限怎么解决
  16. SSH框架 spring 配置中的: scope=&quot;prototype&quot;
  17. 《RabbitMQ Tutorial》译文 第 5 章 主题
  18. toString 方法在数组中的使用
  19. SecureCRT安装
  20. IHttpHandler处理请求api

热门文章

  1. Linux08 /Docker
  2. ajax配合art-template模板引擎的使用
  3. CentOS7 源码编译安装Nginx
  4. TCP 和 UDP,哪个更胜一筹
  5. 前端框架-jQuery自学笔记
  6. Burp Suite Extender Module - 扩展模块
  7. java中实现无限层级的树形结构
  8. C++语法小记---多重继承
  9. Python &quot;按位或&quot;和&quot;按位异或&quot;的区别
  10. ThreadLocal 原理