SpringBoot使用异步任务

1. 开启异步任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.pibigstar;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync //开启异步任务
public class SpringbootDemoApplication {

public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}

2. 编写异步任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

package com.pibigstar.task;

import java.util.concurrent.Future;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

@Component
public class AsyncTask {

@Async //异步方法注解
public Future<Boolean> task1() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(1000);
long end = System.currentTimeMillis();
System.out.println("=====任务1 耗时:"+(end-start)+"======");
//返回true,告诉此任务已完成
return new AsyncResult<Boolean>(true);
}

@Async //异步方法注解
public Future<Boolean> task2() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(800);
long end = System.currentTimeMillis();
System.out.println("=====任务2 耗时:"+(end-start)+"======");
//返回true,告诉此任务已完成
return new AsyncResult<Boolean>(true);
}

@Async //异步方法注解
public Future<Boolean> task3() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(600);
long end = System.currentTimeMillis();
System.out.println("=====任务3 耗时:"+(end-start)+"======");
//返回true,告诉此任务已完成
return new AsyncResult<Boolean>(true);
}
}

3. 启动异步任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.pibigstar.web;

import java.util.concurrent.Future;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.pibigstar.task.AsyncTask;

@RestController
@RequestMapping("/task")
public class AsyncTaskController {

@Autowired
private AsyncTask asyncTask;

@GetMapping("test")
public String test() throws InterruptedException {
long start = System.currentTimeMillis();
Future<Boolean> a = asyncTask.task1();
Future<Boolean> b = asyncTask.task2();
Future<Boolean> c = asyncTask.task3();

//循环到三个任务全部完成
while (!a.isDone()||!b.isDone()||!c.isDone()) {
if (a.isDone()&&b.isDone()&&c.isDone()) {
break;
}
}
long end = System.currentTimeMillis();
String result = "任务完成,一共用时为:"+(end-start)+"毫秒";
System.out.println(result);
return result;
}
}

4. 运行结果

任务1 睡眠了 1000毫秒,任务2 睡眠了800毫秒,任务3 睡眠了600毫秒,如果是同步执行的话三个任务完成应该是2400毫秒,而这里只使用了1005毫秒,说明我们的任务执行确实是异步执行

5. 异步执行使用场景

-------------本文结束感谢您的阅读-------------