Java 如何欺骗CompletableFuture.complete()在其他线程中运行依赖项/阶段? CompletableFuture cf=newcompletablefuture(); cf.完成时((t,可丢弃)->{ System.out.println(Thread.currentThread().toString()); }); cf.complete(新对象());

Java 如何欺骗CompletableFuture.complete()在其他线程中运行依赖项/阶段? CompletableFuture cf=newcompletablefuture(); cf.完成时((t,可丢弃)->{ System.out.println(Thread.currentThread().toString()); }); cf.complete(新对象());,java,completable-future,Java,Completable Future,这将在调用cf.complete()的线程中的complete的BiConsumer回调时运行 如果complete/other lambda不在当前线程中(commonPool()?),而不从另一个线程调用cf.complete()),如何运行此操作 您不能在cd.complete()级别执行此操作。 唯一的办法就是使用 CompletableFuture<Object> cf = new CompletableFuture<>(); cf.whenComplete((

这将在调用cf.complete()的线程中的complete的
BiConsumer
回调时运行


如果complete/other lambda不在当前线程中(
commonPool()
?),而不从另一个线程调用
cf.complete()
),如何运行此操作

您不能在
cd.complete()级别执行此操作。
唯一的办法就是使用

CompletableFuture<Object> cf = new CompletableFuture<>();
cf.whenComplete((t, throwable) -> {
    System.out.println(Thread.currentThread().toString());
});
cf.complete(new Object());
并将执行器作为第二个参数传递

所以它看起来是这样的:

cd.whenCompleteAsync()
Executor Executor=Executors.newSingleThreadExecutor();
CompletableFuture cf=新的CompletableFuture();
cf.whenCompleteTasync((t,可丢弃)->{
System.out.println(Thread.currentThread().toString());
},遗嘱执行人);
cf.complete(新对象());
编辑: 我忘了提到,如果你不想,你不必创建自己的遗嘱执行人。只需使用whenCompleteAsync(),无需第二个参数。然后它将在ForkJoin池的线程中运行代码

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