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配置动态数据源访问多个数据库.但是之前的方案有一些限制(原博客中 ...
随机推荐
- 史上最全的Spring Boot配置文件详解
Spring Boot在工作中是用到的越来越广泛了,简单方便,有了它,效率提高不知道多少倍.Spring Boot配置文件对Spring Boot来说就是入门和基础,经常会用到,所以写下做个总结以便日 ...
- Linux Namespace : Network
Network namespace 在逻辑上是网络堆栈的一个副本,它有自己的路由.防火墙规则和网络设备.默认情况下,子进程继承其父进程的 network namespace.也就是说,如果不显式创建新 ...
- base64编码解码原理
计算机只能处理数字,所以要处理任何文本,只能先将文本转化为数字才行. Bit(bit)(b) 位或比特,是计算机运行的基础,属于二进制的范畴.数据传输大多是以[位]为单位,一个位即代表一个0或者1(即 ...
- vue组件化开发组件拆分原则是什么
原则:可复用.可组合: 两大类:页面组件.功能组件: 除了公共头导航.侧导航.脚部内容,还有:
- A-Text Reverse(文本反向读)
多组数据测试,输入t,表示要测几个,每个语句反向输出. 链接 [https://cn.vjudge.net/contest/235390#problem/A] 解: 就是getchar()和gets( ...
- jQuery基础语法知识梳理
一.attr() attr()方法设置或返回元素的属性. attr(属性名):获取元素属性名的值. attr(属性名,属性值):设置元素属性名的值. 例子: <a href=”http://12 ...
- 软件工程练习:模块化,单元测试,回归测试,TDD
这是<构建之法>实战教学的一部分.适合作为同学们的第二个程序作业. 第一个程序作业: 请看 “概论” 一章的练习,或者老师的题目,例如这个. 作业要求: 软件工程的作业越来越有意思了, 我 ...
- nodejs 中的一些方法
fs.unlink(path, [callback(err)]) //删除文件操作. //path 文件路径 //callback 回调,传递一个异常参数err. ndoe中解决跨域问题 expres ...
- vue上传图片
在用这块代码前需要在主页面index引入<script src="http://at.alicdn.com/t/font_kfbh2nlnqrrudi.js">< ...
- oracle创建表空间、创建用户、授权角色和导入导出用户数据
使用数据库管理员身份登录 -- log as sysdba sqlplus / as sysdba; 创建临时表空间 -- create temporary tablespace create tem ...