启动类
@EnableAsync
异步任务
@Component 扫描组件
@Async 告诉springboot 这是个异步任务
创建四个 异步任务 这里打印出异步执行时间
@Component
public class AsyncTask {
@Async
public Future<Boolean> myAsyncTask1()throws Exception{
long startTime = System.currentTimeMillis();
Thread.sleep(1000);
long endTime = System.currentTimeMillis();
System.out.println("任务①耗时"+(endTime-startTime)+"毫秒");
return new AsyncResult<>(true);
}
@Async
public Future<Boolean> myAsyncTask2()throws Exception{
long startTime = System.currentTimeMillis();
Thread.sleep(1500);
long endTime = System.currentTimeMillis();
System.out.println("任务②耗时"+(endTime-startTime)+"毫秒");
return new AsyncResult<>(true);
}
@Async
public Future<Boolean> myAsyncTask3()throws Exception{
long startTime = System.currentTimeMillis();
Thread.sleep(600);
long endTime = System.currentTimeMillis();
System.out.println("任务③耗时"+(endTime-startTime)+"毫秒");
return new AsyncResult<>(true);
}
@Async
public Future<Boolean> myAsyncTask4()throws Exception{
long startTime = System.currentTimeMillis();
Thread.sleep(700);
long endTime = System.currentTimeMillis();
System.out.println("任务④耗时"+(endTime-startTime)+"毫秒");
return new AsyncResult<>(true);
}
}
调用
@RestController
@RequestMapping("/async")
public class AsyncController {
@Autowired
AsyncTask task;
@RequestMapping("/myAsync")
public String myAsync() throws Exception {
StringBuffer buffer = new StringBuffer("异步执行任务总耗时为:");
long startTime = System.currentTimeMillis();
Future<Boolean> async1 = task.myAsyncTask1();
Future<Boolean> async2 = task.myAsyncTask2();
Future<Boolean> async3 = task.myAsyncTask3();
Future<Boolean> async4 = task.myAsyncTask4();
while (!async1.isDone() || !async2.isDone() ||
!async3.isDone() || !async4.isDone()) {
if (!async1.isDone() && !async2.isDone() && !async3.isDone() && !async4.isDone()) {
break;
}
}
long endTime = System.currentTimeMillis();
buffer.append((endTime - startTime));
buffer.append("毫秒");
System.out.println(buffer);
return buffer.toString();
}
}