【发布时间】:2019-04-11 09:14:46
【问题描述】:
当我使用 ExecutorService 进行异步调用时,它会返回 Future Object。根据它返回的布尔值,我必须记录异步调用的状态。
但是当我尝试从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
}
}
【问题讨论】:
-
是的,你可以,只是不要打电话给
response.get();。或者您可以稍等片刻,然后致电response.isDone() -
但我想根据aysnc响应登录:(
-
因此,您必须等待操作完成(例如通过调用
get())才能获得结果,或者继续执行而不关心结果。您也可以启动另一个线程并在其中调用response.get();,然后在结果可用时记录结果。
标签: java concurrency java-8 future completable-future