Java 8可完善的未来

ayu*_*ush 5 java multithreading future java-8 completable-future

我的问题是如何使用Completable Future.

我有一个实现Callable的类.

public class Executor implements Callable<Collection>
Run Code Online (Sandbox Code Playgroud)

早先习惯做 -

service.submit(collectorService);
Run Code Online (Sandbox Code Playgroud)

哪个会回来的Future<Collection>.但是我们不想再继续使用未来了CompletableFuture.一个想法是我们不需要使用CompletableFuture进行轮询,我们不必等待并阻止它直到它准备就绪.

那么我将如何使用可完成的未来并isDone()callable线程完成时调用函数.

Mik*_*bel 6

给定a CompletableFuture<T> f,您可以启动同步或异步任务,以便在完成时运行:

f.thenApply(result -> isDone(result));      // sync callback
f.thenApplyAsync(result -> isDone(result)); // async callback
Run Code Online (Sandbox Code Playgroud)

......或者,如果您不需要结果:

f.thenRun(() -> isDone());
f.thenRunAsync(() -> isDone());
Run Code Online (Sandbox Code Playgroud)