您必须加入线程以确保其计算完成

Rae*_*ald 5 java multithreading future

我有一个实用方法(用于单元测试,它发生了),它Runnable在另一个线程中执行.它启动线程运行,但不等待Thread完成,而是依赖于Future.该方法的调用者预期get()的是Future.但这足以确保安全发布由...完成的计算Runnable吗?

这是方法:

private static Future<Void> runInOtherThread(final CountDownLatch ready, final Runnable operation) {
    final CompletableFuture<Void> future = new CompletableFuture<Void>();
    final Thread thread = new Thread(() -> {
        try {
            ready.await();
            operation.run();
        } catch (Throwable e) {
            future.completeExceptionally(e);
            return;
        }
        future.complete(null);
    });
    thread.start();
    return future;
}
Run Code Online (Sandbox Code Playgroud)

在调用Future.get()返回后Future,该方法的调用者能否安全地假设Runnable已完成执行,并且其结果已安全发布?

Ste*_*n C 4

不,你不需要join()。呼唤get()未来就足够了。

CompletableFuture接口是 的子类型Future。javadoc声明如下Future

内存一致性影响:异步计算所采取的操作发生在另一个线程中相应操作之后Future.get()

这种事前发生的关系足以确保安全发布get().

此外,get()只有在CompletableFuture完成、异常完成或取消后,调用才会完成。