2016-05-04 19 views
3

CompletableFuture API是相当吓人,很多的接受,和thens和其他的东西;很难说出为什么有不同的选择。如何在不阻塞的情况下启动CompletableFuture并在完成时执行某些操作?

CompletableFuture<?> future = CompletableFuture.supplyAsync(() ->..., executor) 

future.startNonBlocking...((...) -> { callback behavior done when complete } 

基本上,我试图模仿new Thread(() -> dostuff).start()但具有更好的线程池,错误处理等注:其实我并不需要Runnable接口在这里,我一个泛型化一条已有的代码。

什么是启动我的异步任务并在完成时执行行为的正确方法?或处理抛出的异常?

+0

http://www.nurkiewicz.com/2013/05/java-8-definitive-guide-to.html –

回答

2

这里有一个简单的异步回调:

CompletableFuture.supplyAsync(() -> [result]).thenAccept(result -> [action]); 

或者,如果你需要的错误处理:

CompletableFuture.supplyAsync(() -> [result]).whenComplete((result, exception) -> { 
    if (exception != null) { 
     // handle exception 
    } else { 
     // handle result 
    } 
}); 
2
new Thread(() -> dostuff).start() 

意味着dostuff工具的Runnable,所以您可以使用

static CompletableFuture<Void> runAsync(Runnable runnable)  
static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor) 

也。

相关问题