啓動類
@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();
}
}