该CompletableFuture
API相当吓人,很多被接受,然后发生其他事情。很难说出为什么存在不同的选择。
CompletableFuture<?> future = CompletableFuture.supplyAsync(() ->..., executor)
future.startNonBlocking...( (...) -> { callback behavior done when complete }
我基本上是在尝试模仿,new Thread(() -> dostuff).start()
但具有更好的线程池,错误处理等功能。注意:我实际上不需要Runnable
这里的接口,我正在生成一段现有代码。
什么是启动异步任务并在完成后执行行为的正确方法?或处理引发的异常?
这是一个简单的异步回调:
CompletableFuture.supplyAsync(() -> [result]).thenAccept(result -> [action]);
或者,如果您需要错误处理:
CompletableFuture.supplyAsync(() -> [result]).whenComplete((result, exception) -> {
if (exception != null) {
// handle exception
} else {
// handle result
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句