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多线程的更多相关文章

  1. 【转】Spring Boot 构建应用——快速构建 Spring Boot 应用

    Spring Boot 简化了 Spring 应用开发,不需要配置就能运行 Spring 应用,Spring Boot 的自动配置是通过 Spring 4.x 的条件注解 @Conditional 来 ...

  2. Spring Boot 定时任务单线程和多线程

    Spring Boot 的定时任务: 第一种:把参数配置到.properties文件中: 代码: package com.accord.task; import java.text.SimpleDat ...

  3. spring boot 2X中@Scheduled实现定时任务及多线程配置

    使用@Scheduled 可以很容易实现定时任务 spring boot的版本 2.1.6.RELEASE package com.abc.demo.common; import org.slf4j. ...

  4. Spring Boot 定时+多线程执行

    Spring Boot 定时任务有多种实现方式,我在一个微型项目中通过注解方式执行定时任务. 具体执行的任务,通过多线程方式执行,单线程执行需要1小时的任务,多线程下5分钟就完成了. 执行效率提升10 ...

  5. spring boot 并发请求,其他系统接口,丢失request的header信息【多线程、线程池、@Async 】

    场景:一次迭代在灰度环境发版时,测试反馈说我开发的那个功能,查询接口有部分字段数据是空的,后续排查日志,发现日志如下: feign.RetryableException: cannot retry d ...

  6. (转)spring boot注解 --@EnableAsync 异步调用

    原文:http://www.cnblogs.com/azhqiang/p/5609615.html EnableAsync注解的意思是可以异步执行,就是开启多线程的意思.可以标注在方法.类上. @Co ...

  7. spring boot注解 --@EnableAsync 异步调用

    EnableAsync注解的意思是可以异步执行,就是开启多线程的意思.可以标注在方法.类上. @Component public class Task { @Async public void doT ...

  8. spring boot / cloud (十九) 并发消费消息,如何保证入库的数据是最新的?

    spring boot / cloud (十九) 并发消费消息,如何保证入库的数据是最新的? 消息中间件在解决异步处理,模块间解耦和,和高流量场景的削峰,等情况下有着很广泛的应用 . 本文将跟大家一起 ...

  9. 如何通过Spring Boot配置动态数据源访问多个数据库

    之前写过一篇博客<Spring+Mybatis+Mysql搭建分布式数据库访问框架>描述如何通过Spring+Mybatis配置动态数据源访问多个数据库.但是之前的方案有一些限制(原博客中 ...

随机推荐

  1. python程序爬虫总是崩溃

    写的一个爬虫程序,主要用到以下库.但是伴随着代码增多,功能增多.经常性的程序崩溃现象,逐渐显现. pyqt5_5.8.2,requests.get,selenium+chorme,threading. ...

  2. C# 下载文件

    最近一段时间,真的是太忙太忙了!经历了自我毕业以来最忙碌的一个项目! 说起这个项目,我有万千感慨 且不说技术能力,也无需谈论项目需求.单就项目压力,日常加班,周六日补班而言,我相信很多人是扛不住的! ...

  3. mysql安装与配置详情

    一.概述 MySQL版本:5.6.43 下载地址:mysql-installer-community-5.6.43.0,提取码:tgmk 客户端工具:NavicatforMySQL 下载地址:Navi ...

  4. Spring Boot 2.0(八):Spring Boot 集成 Memcached

    Memcached 介绍 Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站 ...

  5. Linux iptables 命令

    iptables 是 Linux 管理员用来设置 IPv4 数据包过滤条件和 NAT 的命令行工具.iptables 工具运行在用户态,主要是设置各种规则.而 netfilter 则运行在内核态,执行 ...

  6. Plugin 'Lombok Plugin' is incompatible with this installation

    作者:13 GitHub:https://github.com/ZHENFENG13 版权声明:本文为原创文章,未经允许不得转载. Installation Error Plugin 'Lombok ...

  7. Filebeat简介

    原文地址:http://blog.51cto.com/seekerwolf/2110174 收集日志的目的是有效的利用日志,有效利用日志的前提是日志经过格式化符合我们的要求,这样才能真正的高效利用收集 ...

  8. 剑指Offer-- 二叉搜索树中和为某一值的路径

    输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径.路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径. 本身题目不是很难,但是因为刚接触pyhon,对一些对象的传 ...

  9. RabbitMQ 安装与使用

    RabbitMQ 安装与使用   前言 吃多了拉就是队列,吃饱了吐就是栈 使用场景 对操作的实时性要求不高,而需要执行的任务极为耗时:(发送短信,邮件提醒,更新文章阅读计数,记录用户操作日志) 存在异 ...

  10. idea 方便的设置代码段

    使用快捷键(ctrl+alt+s)找到:从idea的菜单File->Settings->Editor->Live Templates 先添加Template Group,然后添加Li ...