springboot ListenableFuture 异步回调

38次阅读

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

定义 ListenableFuture
public void getListenableFuture() {
ListenableFutureTask<String> task = new ListenableFutureTask<String>(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(5000); // 模拟耗时操作
return “success”;
}
});
task.addCallback(new ListenableFutureCallback<String>() {
@Override
public void onFailure(Throwable throwable) {
System.out.println(“ 调用失败 ”);
}

@Override
public void onSuccess(String s) {
System.out.println(“ 调用成功:” + s);
}
});
Executors.newSingleThreadExecutor().submit(task);
}
调用
@GetMapping(“test-listen-future”)
public void testListenableFuture() {
for (int i = 0; i < 10; i++) {
System.out.println(“i = ” + i);
}
asyncService.getListenableFuture();
for (int j = 0; j < 10; j++) {
System.out.println(“j = ” + j);
}
}
执行顺序

循环 i
循环 j
调用成功:success

代码:springboot ListenableFuture 异步回调

正文完
 0