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 }
执行结果
![](https://i-blog.csdnimg.cn/blog_migrate/67a1110cfcebc45208b2416d6ba4cbdf.png)
handle1、handle2、handle3的执行结果为乱序,不可预估。这样最简易的通过2个注解即完成异步线程的调用了。