定义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);
        }
    }

执行顺序

  1. 循环i
  2. 循环j
  3. 调用成功:success

代码:springboot ListenableFuture 异步回调


lijingyulee
91 声望7 粉丝