gpt4 book ai didi

Java future : How to unblock Main thread while executing Aysnc call

转载 作者:行者123 更新时间:2023-11-29 06:49:04 24 4
gpt4 key购买 nike

当我使用 ExecutorService 进行异步调用时,它返回 Future 对象。根据它返回的 boolean 值,我必须记录异步调用的状态。

但是当我尝试从 future 对象调用方法 get 方法时,它会阻塞主线程执行。

是否可以解除阻塞主线程执行?

public class FutureExample {

static HystrixCommand<Boolean> hystrixCommand;

public FutureExample(HystrixCommand<Boolean> hystrixCommand){
FutureExample.hystrixCommand = hystrixCommand;
}

public static void main(String[] args) throws InterruptedException, ExecutionException {


Boolean something = asyncCall();

if(something) {
System.out.println("Future task is done");
}

System.out.println("Don't wait for async call");

}

private static Boolean asyncCall() throws InterruptedException, ExecutionException {

Future<Boolean> response = hystrixCommand.queue(); // Aysnc Call to remote server

return response.get(); //this is blocking main thread
}

}

最佳答案

futures 的好处是能够释放线程直到答案到达。所以我建议你使用 Future 实现,比如 CompletableFuture:

final ExecutorService executorService = Executors.newFixedThreadPool(10);

CompletableFuture.supplyAsync(() -> {
try {
return hystrixCommand.queue();
} catch (Exception e) {
return false;
}
}, executorService);

这将在另一个线程上工作,当那个 future 结束时它就会完成。

关于Java future : How to unblock Main thread while executing Aysnc call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55628843/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com