springBoot服务整合线程池ThreadPoolTaskExecutor与@Async详解使用
ThreadPoolExecutor:=======这个是java自己实现的线程池执行类,基本上创建线程池都是通过这个类进行的创建。
ThreadPoolTaskExecutor:========这个是springboot基于ThreadPoolExecutor实现的一个线程池执行类。
注意:
在springboot当中,如果没有配置线程池的话,springboot会自动配置一个ThreadPoolTaskExecutor线程池到bean当中,我们调用只需要
@Autowired
ThreadPoolTaskExecutor threadPoolTaskExecutor;
第一步: 首先在application启动类添加@EnableAsync
@SpringBootApplication
@EnableAsync //首先在application启动类添加@EnableAsync
public class ThreadpoolApplication {
public static void main(String[] args) {
SpringApplication.run(ThreadpoolApplication.class, args);
}
}
第二步:配置线程池,不配置的话使用springboot默认的线程池。
package com.aswatson.csc.task.conf; import java.util.concurrent.Executor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @Configuration
@EnableAsync
public class AsyncThreadConfiguration { @Bean("kafkaThreadExecutor")
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);//核心线程数
executor.setMaxPoolSize(20);//最大线程数
executor.setKeepAliveSeconds(60);//空闲线程存活时间
executor.setThreadNamePrefix("kafkaThreadAsync-");
executor.initialize();
return executor;
} }
第三步:测试1:在需要异步执行的方法上加上@Async注解。
@Service
public class AsyncTest {
protected final Logger logger = LoggerFactory.getLogger(this.getClass()); @Async
public void hello(String name){
customerEventLogMapper.insert(customerEventLog);
logger.info("异步线程启动 started."+name);
}
}
第四步:测试2:使用注入的模式:
package com.example.apidemo.completableFutrue; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service; import java.time.LocalDateTime; @Service
public class AsyncService { @Autowired
ThreadPoolTaskExecutor threadPoolTaskExecutor; public void addEventLog(String buId, String status){
CustomerEventLogPO customerEventLog = new CustomerEventLogPO();
customerEventLog.setUuid(uuid);
customerEventLog.setStatus(status);
customerEventLog.setCreated(LocalDateTime.now());
customerEventLogMapper.insert(customerEventLog); threadPoolTaskExecutor.submit(new Thread(()->{
customerEventLogMapper.insert(customerEventLog);
})); //submit有返回值 threadPoolTaskExecutor.execute(new Thread(()->{
customerEventLogMapper.insert(customerEventLog);
})); //execute无返回值
} }
注意: 如果配置多个线程池,该如何指定线程池呢?
方式1: @Resources("kafkaThreadExecutor")。
方式2: 如果有多个线程池,但是在@Async注解里面没有指定的话,会默认加载第一个配置的线程池。
======================================================================================================================================================================
// @Bean()的拒绝策略:
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
拒绝策略:如果(总任务数 - 核心线程数 - 任务队列数)-(最大线程数 - 核心线程数)> 0 的话,则会出现线程拒绝。举例:( 12 - 5 - 2 ) - ( 8 - 5 ) > 0,会出现线程拒绝。线程拒绝又分为 4 种策略,分别为:
- CallerRunsPolicy():交由调用方线程运行,比如 main 线程。
- AbortPolicy():直接抛出异常。
- DiscardPolicy():直接丢弃。
- DiscardOldestPolicy():丢弃队列中最老的任务。
springBoot服务整合线程池ThreadPoolTaskExecutor与@Async详解使用的更多相关文章
- java线程池的使用与详解
java线程池的使用与详解 [转载]本文转载自两篇博文: 1.Java并发编程:线程池的使用:http://www.cnblogs.com/dolphin0520/p/3932921.html ...
- 从线程池到synchronized关键字详解
线程池 BlockingQueue synchronized volatile 前段时间看了一篇关于"一名3年工作经验的程序员应该具备的技能"文章,倍受打击.很多熟悉而又陌生的知识 ...
- Java线程池(ThreadPool)详解
线程五个状态(生命周期): 线程运行时间 假设一个服务器完成一项任务所需时间为:T1 创建线程时间,T2 在线程中执行任务的时间,T3 销毁线程时间. 如果:T1 + T3 远大于 T2,则可以 ...
- java线程池ThreadPoolExecutor类使用详解
在<阿里巴巴java开发手册>中指出了线程资源必须通过线程池提供,不允许在应用中自行显示的创建线程,这样一方面是线程的创建更加规范,可以合理控制开辟线程的数量:另一方面线程的细节管理交给线 ...
- 【java】之常用四大线程池用法以及ThreadPoolExecutor详解
为什么用线程池? 1.创建/销毁线程伴随着系统开销,过于频繁的创建/销毁线程,会很大程度上影响处-理效率2.线程并发数量过多,抢占系统资源从而导致阻塞3.对线程进行一些简单的管理 在Java中,线程池 ...
- Java常用四大线程池用法以及ThreadPoolExecutor详解
为什么用线程池? 1.创建/销毁线程伴随着系统开销,过于频繁的创建/销毁线程,会很大程度上影响处-理效率 2.线程并发数量过多,抢占系统资源从而导致阻塞 3.对线程进行一些简单的管理 在Java中,线 ...
- 【多线程】Java线程池七个参数详解
/** * Creates a new {@code ThreadPoolExecutor} with the given initial * parameters. * * @param coreP ...
- Java线程池七个参数详解
Java多线程开发时,常常用到线程池技术,这篇文章是对创建java线程池时的七个参数的详细解释. 从源码中可以看出,线程池的构造函数有7个参数,分别是corePoolSize.maximumPoolS ...
- SpringBoot异步及线程池配置
异步方法注解@Async 在SpringBoot中进行异步处理,可以使用异步注解@Async和@EnableAsync. @Async注解表示异步,如:@Async("asyncServic ...
随机推荐
- python3 用multiprocessing模块传递多个参数
from datetime import datetime from time import sleep import numpy as np import multiprocessing # fro ...
- python 给多个变量赋值
# assign values directly a = b = 'hello' a, b = 1, 2 print(b, type(b)) assert a == 1 and b == 2 # as ...
- Ubuntu / CoreOS修改DNS配置
不要直接手动修改文件 /etc/resolv.conf 安装好Ubuntu之后设置了静态IP地址,再重启后就无法解析域名.想重新设置一下DNS,打开/etc/resolv.conf cat /etc/ ...
- SQL-DELETE触发器练习
&练习一 如下所示三张表( student,grade,student_updata_before ): student表 grade表 Student_update_before表 # 触发 ...
- 在C#中将图像转换为BASE64
本教程说明如何在C#.NET Windows Forms Application中将图像转换为base64字符串,以及将base64字符串转换为图像.您可以创建一个新的Windows窗体应用程序项目来 ...
- 1.Java 基础
1. JDK 和 JRE 有什么区别? jdk:开发工具包,jre:java运行环境 jdk包含了jre和java开发环境,如编译java源码的编译器javac,还包含了许多java程序调试和分析的工 ...
- composer 下载包慢
方法一: 修改 composer 的全局配置文件(推荐方式) 打开命令行窗口(windows用户)或控制台(Linux.Mac 用户)并执行如下命令: composer config -g repo. ...
- Docker DevOps实战:Docker+Jenkins+Python+Pytest+Allure(1)- 创建Jenkins容器、安装Python环境、安装项目依赖类库、安装Allure报告插件
前言: 本文实操笔记参照菠萝笔记,安装过程中的坑大家可以参考下 创建Jenkins容器 # 下载Jenkins镜像 [root@localhost ~]# docker pull jenkins/je ...
- javascript LinkedList js 双向循环链表 Circular Linked List
javascript LinkedList: function Node(elem, prev, next) { this.elem = elem; this.prev = prev ? prev : ...
- 让selenium规避网站的检测
在使用selenium对某些网站模拟访问的时候会被检测出来,检测出来之后就有可能拿不到我们想要的数据,那么我们怎么可以规避掉呢? 在使用谷歌浏览器的时候我们右键-检查-console-输入window ...