今天,我尝试了CompletableFuture
Java 8中的“新”功能,但在找不到runAsync(Callable)
方法时感到困惑。我可以按照如下所示自己完成操作,但是为什么缺少此方法(对我来说是非常明显和有用的实用程序方法)?上午我失去了一些东西?
public static <T> CompletableFuture<T> asFuture(Callable<? extends T> callable, Executor executor) {
CompletableFuture<T> future = new CompletableFuture<>();
executor.execute(() -> {
try {
future.complete(callable.call());
} catch (Throwable t) {
future.completeExceptionally(t);
}
});
return future;
}
你应该使用 supplyAsync(Supplier<U>)
通常,lambda和受检查的异常不能很好地协同工作,并且CompletableFuture
通过设计避免了受检查的异常。虽然在您的情况下应该没问题。
相关主题:
http://cs.oswego.edu/pipermail/concurrency-interest/2012-December/010486.html
http://cs.oswego.edu/pipermail/concurrency-interest/2014-August/012911.html
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句