1.启动类里面使用@EnableAsync注解开启功能,自动扫描
2.在方法上面加上@Async
我这里写了一个测试类
@Component
@Async
public class AsyncTask {
public void task1() throws InterruptedException {
long begin = System.currentTimeMillis();
Thread.sleep(1000);
long end = System.currentTimeMillis();
long total = end - begin;
System.err.println("任务1耗时:"+total);
}
public void task2() throws InterruptedException {
long begin = System.currentTimeMillis();
Thread.sleep(2000);
long end = System.currentTimeMillis();
long total = end - begin;
System.err.println("任务2耗时:"+total);
}
public void task3() throws InterruptedException {
long begin = System.currentTimeMillis();
Thread.sleep(3000);
long end = System.currentTimeMillis();
long total = end - begin;
System.err.println("任务3耗时:"+total);
}
public Future<String> task4() throws InterruptedException { long begin = System.currentTimeMillis(); Thread.sleep(3000); long end = System.currentTimeMillis(); long total = end - begin; System.err.println("任务4耗时:"+total); return new AsyncResult<String>("任务4"); }
}
然后在controller 加入一个方法调用这个异步的方法任务
/*
* 异步任务
* */
@GetMapping("async_total")
public long AsyncTotal() throws InterruptedException {
long begin = System.currentTimeMillis();
asyncTask.task1();
asyncTask.task2();
asyncTask.task3();
Future<String> task4 = asyncTask.task4();
if(task4.isDone()){ System.err.println("------>返回成功"); break; }
long end = System.currentTimeMillis();
long counttotal = end - begin;
return counttotal;
}
如果为同步这里我们最少需要花费6秒因为我三个任务一起等待了6秒
但是我使用了异步我请求这个只花费了2秒钟
task4 这是有返回类型的就是得到此次调用的返回 并用isDone 判断是否有返回