springboot 异步回调

5次阅读

共计 1509 个字符,预计需要花费 4 分钟才能阅读完成。

定义异步方法,使用 Future<T> 来返回异步调用的结果
@Async
public Future<String> firstTask() throws InterruptedException {
System.out.println(“ 开始做任务一 ”);
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println(“ 完成任务一,当前线程:” + Thread.currentThread().getName() + “,耗时:” + (end – start) + “ 毫秒 ”);
return new AsyncResult<>(“ 任务一完成 ”);
}

@Async
public Future<String> secondTask() throws InterruptedException {
System.out.println(“ 开始做任务二 ”);
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println(“ 完成任务二,当前线程:” + Thread.currentThread().getName() + “,耗时:” + (end – start) + “ 毫秒 ”);
return new AsyncResult<>(“ 任务二完成 ”);
}

@Async
public Future<String> thirdTask() throws InterruptedException {
System.out.println(“ 开始做任务三 ”);
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println(“ 完成任务三,当前线程:” + Thread.currentThread().getName() + “,耗时:” + (end – start) + “ 毫秒 ”);
return new AsyncResult<>(“ 任务三完成 ”);
}
调用
@GetMapping(“test-future”)
public void testFuture() {
try {
Future<String> result1 = asyncService.firstTask();
Future<String> result2 = asyncService.secondTask();
Future<String> result3 = asyncService.thirdTask();
while (true) {
if (result1.isDone() && result2.isDone() && result3.isDone()) {
System.out.println(“ 执行异步回调 ”);
break;
}
}
System.out.println(“ 异步回调结束 ”);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
调用结果
开始做任务一
开始做任务二
开始做任务三
完成任务二,当前线程:task-2,耗时:896 毫秒
完成任务一,当前线程:task-1,耗时:7448 毫秒
完成任务三,当前线程:task-3,耗时:7901 毫秒
执行异步回调
异步回调结束
代码:异步回调

正文完
 0