Java Future对象用于获取由并行线程(Executors)执行的异步计算结果。我们调用Future.get()方法并等待结果准备就绪。此示例展示了一种从未来中检索结果的非阻塞方式。java-implement-java-non-blocking-futures。
NonBlockingExecutor executor = new NonBlockingExecutor(Executors.newSingleThreadExecutor());
NonBlockingFuture<Integer> future = executor.submitNonBlocking(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
String threadName = Thread.currentThread().getName();
System.out.println(threadName);
//print -> pool-1-thread-1
return 1;
}
});
future.setHandler(new FutureHandler<Integer>() {
@Override
public void onSuccess(Integer value) {
String threadName = Thread.currentThread().getName();
System.out.println(threadName);
//print -> pool-1-thread-1
}
@Override
public void onFailure(Throwable e) {
System.out.println(e.getMessage());
}
});
Thread.sleep(50000);
在并行执行完成后,将调用此onSuccess()方法。问题是,onSuccess()方法不在主线程上运行。我想在主线程上执行onSuccess()方法。我该如何解决这个问题。谢谢。