相关疑难解决方法(0)

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

我有一个实用方法(用于单元测试,它发生了),它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已完成执行,并且其结果已安全发布?

java multithreading future

5
推荐指数
1
解决办法
111
查看次数

标签 统计

future ×1

java ×1

multithreading ×1