Java多线程开发系列之Springboot 中异步请求方法的使用

本文介绍了如何在SpringBoot应用中实现异步处理,包括通过@EnableAsync和@Async注解简化异步方法的声明,以及自定义线程池以满足特定业务需求。通过示例展示了默认线程池配置可能导致的问题,并详细解释了如何配置自定义线程池,确保线程的正确管理和任务执行顺序。同时,提到了使用Future接口捕获异步方法的返回结果。
摘要由CSDN通过智能技术生成

Springboot 中异步线程的使用

在过往的后台开发中,我们往往使用java自带的线程或线程池,来进行异步的调用。这对于效果来说没什么,甚至可以让开发人员对底层的状况更清晰,但是对于代码的易读性和可维护性却非常的差。

开发人员在实际使用过程中,应该更多的将精力放置在业务代码的书写过程中,而不是系统代码的维护中。你需要懂,但是不需要你直接维护去写,这才是编程语言的风向标。(这也是为什么spring在目前的java开发中,占用比重如此之大的原因之一)

下面来看使用Springboot 来实现异步调用的集中场景

一、简易注解,无需额外配置

1、添加@EnableAsync 到启动类(或者线程池配置类中)

2、添加@Async到需要异步执行的方法中

代码如下:

启动类

@EnableAsync
@SpringBootApplication
 public class DemoLearnSpringbootApplication {
 
     public static void main(String[] args) {
         SpringApplication.run(DemoLearnSpringbootApplication.class, args);
     }
 }

调用类
 

 1 @Component
 2 public class SimpleAsyncDemo {
 3     @Autowired
 4     private SimpleTaskHandler simpleTaskHandler;
 5 
 6 
 7     @PostConstruct
 8     public void execTaskHandler1() {
 9         try {
10             simpleTaskHandler.handle1(2);
11             simpleTaskHandler.handle2(2);
12             simpleTaskHandler.handle3(2);
13             simpleTaskHandler.handle1(2);
14             simpleTaskHandler.handle2(2);
15             simpleTaskHandler.handle3(2);
16             simpleTaskHandler.handle1(2);
17             simpleTaskHandler.handle2(2);
18             simpleTaskHandler.handle3(2);
19         } catch (InterruptedException e) {
20             e.printStackTrace();
21         }
22     }
23   
24 }

被异步调用的类

 1 @Component
 2 public class SimpleTaskHandler {
 3 
 4     public void printCurrentTime(String key) {
 5         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 6         System.out.println(format.format(new Date()) + "***" + key + "****" + Thread.currentThread().getName());
 7     }
 8 
 9     @Async
10     public void handle1(int time) throws InterruptedException {
11         TimeUnit.SECONDS.sleep(time);
12         printCurrentTime("handle1");
13     }
14 
15     @Async
16     public void handle2(int time) throws InterruptedException {
17         TimeUnit.SECONDS.sleep(time);
18         printCurrentTime("handle2");
19     }
20 
21     @Async
22     public void handle3(int time) throws InterruptedException {
23         TimeUnit.SECONDS.sleep(time);
24         printCurrentTime("handle3");
25     }
26 
27 
28 }

执行结果

handle1、handle2、handle3的执行结果为乱序,不可预估。这样最简易的通过2个注解即完成异步线程的调用了。

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值