How to retrieve the return value in asynchronous Java thread?

There are several common methods for asynchronous threads to retrieve return values in Java.

  1. By using the Future interface, you can obtain the return value of an asynchronous thread by using the get() method provided by the Future interface and the FutureTask class.
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<Integer> future = executor.submit(() -> {
    // 异步任务
    return 1;
});

try {
    Integer result = future.get();
    System.out.println("异步任务的返回值为:" + result);
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
}
  1. By using the CompletableFuture class, which is an implementation of the Future in Java 8, you can handle the return values of asynchronous tasks.
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    // 异步任务
    return 1;
});

future.thenAccept(result -> {
    System.out.println("异步任务的返回值为:" + result);
});
  1. Using a callback function allows you to retrieve the return value after the asynchronous task has been completed.
ExecutorService executor = Executors.newFixedThreadPool(1);
executor.submit(() -> {
    // 异步任务
    int result = 1;
    
    // 调用回调函数处理返回值
    callbackFunction(result);
});

public void callbackFunction(int result) {
    System.out.println("异步任务的返回值为:" + result);
}

These are some commonly used methods in Java for retrieving return values from asynchronous threads. Depending on the specific situation, you can choose the method that suits you best.

Leave a Reply 0

Your email address will not be published. Required fields are marked *