Spring boot多线程
1、配置线程配置类
package test; import java.util.concurrent.Executor; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @Configuration
@ComponentScan("test")
@EnableAsync
// 线程配置类
public class AsyncTaskConfig implements AsyncConfigurer { // ThredPoolTaskExcutor的处理流程
// 当池子大小小于corePoolSize,就新建线程,并处理请求
// 当池子大小等于corePoolSize,把请求放入workQueue中,池子里的空闲线程就去workQueue中取任务并处理
// 当workQueue放不下任务时,就新建线程入池,并处理请求,如果池子大小撑到了maximumPoolSize,就用RejectedExecutionHandler来做拒绝处理
// 当池子的线程数大于corePoolSize时,多余的线程会等待keepAliveTime长时间,如果无请求可处理就自行销毁 @Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);// 最小线程数
taskExecutor.setMaxPoolSize(10);// 最大线程数
taskExecutor.setQueueCapacity(25);// 等待队列 taskExecutor.initialize(); return taskExecutor;
} @Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
2、定义线程执行任务类
package test; import java.util.Random;
import java.util.concurrent.Future; import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service; @Service
// 线程执行任务类
public class AsyncTaskService { Random random = new Random();// 默认构造方法 @Async
// 表明是异步方法
// 无返回值
public void executeAsyncTask(Integer i) {
System.out.println("执行异步任务:" + i);
} /**
* 异常调用返回Future
*
* @param i
* @return
* @throws InterruptedException
*/
@Async
public Future<String> asyncInvokeReturnFuture(int i) throws InterruptedException {
System.out.println("input is " + i);
Thread.sleep(1000 * random.nextInt(i)); Future<String> future = new AsyncResult<String>("success:" + i);// Future接收返回值,这里是String类型,可以指明其他类型 return future;
}
}
3、调用
package test; import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.task.TaskRejectedException; public class Application { public static void main(String[] args) throws InterruptedException, ExecutionException {
// testVoid(); testReturn();
} // 测试无返回结果
private static void testVoid() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AsyncTaskConfig.class);
AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class); // 创建了20个线程
for (int i = 1; i <= 20; i++) {
asyncTaskService.executeAsyncTask(i);
} context.close();
} // 测试有返回结果
private static void testReturn() throws InterruptedException, ExecutionException {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AsyncTaskConfig.class);
AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class); List<Future<String>> lstFuture = new ArrayList<Future<String>>();// 存放所有的线程,用于获取结果 // 创建100个线程
for (int i = 1; i <= 100; i++) {
while (true) {
try {
// 线程池超过最大线程数时,会抛出TaskRejectedException,则等待1s,直到不抛出异常为止
Future<String> future = asyncTaskService.asyncInvokeReturnFuture(i);
lstFuture.add(future); break;
} catch (TaskRejectedException e) {
System.out.println("线程池满,等待1S。");
Thread.sleep(1000);
}
}
} // 获取值。get是阻塞式,等待当前线程完成才返回值
for (Future<String> future : lstFuture) {
System.out.println(future.get());
} context.close();
}
}
maven配置
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>TestAysc</groupId>
<artifactId>TestAysc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>1.5.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
</dependencies>
</project>
结果展示:
1、无返回结果

2、有返回结果

Spring boot多线程的更多相关文章
- 【转】Spring Boot 构建应用——快速构建 Spring Boot 应用
Spring Boot 简化了 Spring 应用开发,不需要配置就能运行 Spring 应用,Spring Boot 的自动配置是通过 Spring 4.x 的条件注解 @Conditional 来 ...
- Spring Boot 定时任务单线程和多线程
Spring Boot 的定时任务: 第一种:把参数配置到.properties文件中: 代码: package com.accord.task; import java.text.SimpleDat ...
- spring boot 2X中@Scheduled实现定时任务及多线程配置
使用@Scheduled 可以很容易实现定时任务 spring boot的版本 2.1.6.RELEASE package com.abc.demo.common; import org.slf4j. ...
- Spring Boot 定时+多线程执行
Spring Boot 定时任务有多种实现方式,我在一个微型项目中通过注解方式执行定时任务. 具体执行的任务,通过多线程方式执行,单线程执行需要1小时的任务,多线程下5分钟就完成了. 执行效率提升10 ...
- spring boot 并发请求,其他系统接口,丢失request的header信息【多线程、线程池、@Async 】
场景:一次迭代在灰度环境发版时,测试反馈说我开发的那个功能,查询接口有部分字段数据是空的,后续排查日志,发现日志如下: feign.RetryableException: cannot retry d ...
- (转)spring boot注解 --@EnableAsync 异步调用
原文:http://www.cnblogs.com/azhqiang/p/5609615.html EnableAsync注解的意思是可以异步执行,就是开启多线程的意思.可以标注在方法.类上. @Co ...
- spring boot注解 --@EnableAsync 异步调用
EnableAsync注解的意思是可以异步执行,就是开启多线程的意思.可以标注在方法.类上. @Component public class Task { @Async public void doT ...
- spring boot / cloud (十九) 并发消费消息,如何保证入库的数据是最新的?
spring boot / cloud (十九) 并发消费消息,如何保证入库的数据是最新的? 消息中间件在解决异步处理,模块间解耦和,和高流量场景的削峰,等情况下有着很广泛的应用 . 本文将跟大家一起 ...
- 如何通过Spring Boot配置动态数据源访问多个数据库
之前写过一篇博客<Spring+Mybatis+Mysql搭建分布式数据库访问框架>描述如何通过Spring+Mybatis配置动态数据源访问多个数据库.但是之前的方案有一些限制(原博客中 ...
随机推荐
- BZOJ3309 DZY Loves Maths 莫比乌斯反演、线性筛
传送门 推式子(默认\(N \leq M\)): \(\begin{align*} \sum\limits_{i=1}^N \sum\limits_{j=1}^Mf(gcd(i,j)) & = ...
- 关于GitHub的Hello Word
最近GitHub一直是最火的配置库技术之一,各个技术大牛也都纷纷入驻GitHub 我每天都打交道的DITA-OT开源项目也宣布迁入GitHub. 那么GitHub到底有什么过人之处呢?给各位先扫个盲. ...
- kmeans聚类理论篇
前言 kmeans是最简单的聚类算法之一,但是运用十分广泛.最近在工作中也经常遇到这个算法.kmeans一般在数据分析前期使用,选取适当的k,将数据分类后,然后分类研究不同聚类下数据的特点. 本文记录 ...
- 微软Ignite2018——微软宣布新的学习平台:Microsoft Learn
Ignite 2018 首日感受 头一次参加美国的微软 Ignite 大会,确实规模比国内的大不少.23日是 MVP & RD 的 Pre Day(MVP即Most Valuable Prof ...
- 一文看懂Transformer内部原理(含PyTorch实现)
Transformer注解及PyTorch实现 原文:http://nlp.seas.harvard.edu/2018/04/03/attention.html 作者:Alexander Rush 转 ...
- Flask序列化
我们在做后台接口的时候,对于返回值,用的最多的就是json数据格式 flask中,返回json数据格式,我们可以用到flask的jsonify函数. 对于基础序列是可以直接序列化的,但是更多的情况下, ...
- java 类与类,类与接口 ,接口与接口关系
类: 生活中类是人们对客观事物不断认识而产生的抽象概念,而对象则是现实生活中的一个个实体 面向对象程序设计中,对象是程序的基本单位,相似的对象像变量和类型的关系一样归并到一类,所以,并不先具体地定义对 ...
- Vue2 实现树形菜单(多级菜单)功能模块
结构示意图 ├── index.html ├── main.js ├── router │ └── index.js # 路由配置文件 ├── components # 组件目录 │ ├── App. ...
- 在java中怎样获得当前日期时间
Calendar cal = Calendar.getInstance(); java.text.SimpleDateFormat sdf = new SimpleDateFormat(&quo ...
- 在Git中添加一个项目
首先保证Git服务器正确配置,管理员机器可正常连接并使用Git. 第一步:在服务器上新建一个项目仓库 切换到git用户: a@ubuntu:/home/git$ su - git $ cd /home ...