乐趣区

springboot ListenableFuture 异步回调

定义 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 异步回调

退出移动版