2017-08-08 33 views
1
CompletableFuture<Object> cf = new CompletableFuture<>(); 
cf.whenComplete((t, throwable) -> { 
    System.out.println(Thread.currentThread().toString()); 
}); 
cf.complete(new Object()); 

这将运行whenComplete的BiConsumer在线程中调用cf.complete)回调(如何欺骗CompletableFuture.complete()在其他线程中运行dependents/stages?

我怎样才能在当前线程(commonPool()?)无法运行此whenComplete /其他lambda表达式,而不是调用cf.complete()另一个线程?

回答

2

你不能在cd.complete()这个级别做到这一点。 的唯一方法是使用

cd.whenCompleteAsync() 

并传递的执行作为第二个参数。

因此,这将是这样的:

Executor executor = Executors.newSingleThreadExecutor(); 
CompletableFuture<Object> cf = new CompletableFuture<>(); 
cf.whenCompleteAsync((t, throwable) -> { 
    System.out.println(Thread.currentThread().toString()); 
}, executor); 
cf.complete(new Object()); 

编辑: 我忘了提,你没有创建自己的遗嘱执行人,如果你不想要的。你可以简单地使用没有第二个参数的whenCompleteAsync()。然后它将运行ForkJoin池线程中的代码。