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

執行順序

  1. 循環i
  2. 循環j
  3. 調用成功:success

代碼:springboot ListenableFuture 異步回調java

相關文章
相關標籤/搜索