java - 如何使用 runAsync 等待完整的 future 完全完成?

标签 java java.util.concurrent completable-future

此测试失败:

package com.stackoverflow.demo;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ForkJoinPool;

import org.junit.Assert;
import org.junit.Test;

public class AsyncTest {

    @Test
    public void test1() {
        Assert.assertTrue("please run this test in a machine with 2 or more cores", ForkJoinPool.getCommonPoolParallelism() > 1);

        CompletableFuture<String> cf = CompletableFuture.completedFuture("ok");
        ConcurrentLinkedQueue<String> out = new ConcurrentLinkedQueue<>();

        cf.thenRunAsync(() -> {
            out.add("one");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            out.add("two");
        }, ForkJoinPool.commonPool());

        cf.join();

        Assert.assertEquals(2, out.size());
    }

}

我很惊讶,因为我预料到了 cf.join()考虑所有附加任务。我确信文档中的某个地方说 join只等待初始任务,但不知何故我错过了。

如何获得我想要的行为:等待 CompletableFuture 及其所有附加子任务完成

最佳答案

校对我的帖子时修复了它:

public class AsyncTest {

    @Test
    public void test1() {
        Assert.assertTrue("please run this test in a machine with 2 or more cores", ForkJoinPool.getCommonPoolParallelism() > 1);

        CompletableFuture<String> cf = CompletableFuture.completedFuture("ok");
        ConcurrentLinkedQueue<String> out = new ConcurrentLinkedQueue<>();

        CompletableFuture<Void> cf2 = cf.thenRunAsync(() -> {
            out.add("one");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            out.add("two");
        }, ForkJoinPool.commonPool());

        cf2.join();

        Assert.assertEquals(2, out.size());
    }

}

关于java - 如何使用 runAsync 等待完整的 future 完全完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58477482/

相关文章:

java - 类型与有界通配符不匹配? super 类型

multithreading - 并行执行一个任务 'n' 次

java - 对来自异步线程的信号使用静态 boolean 值与 AtomicBoolean 之间的区别

java - 如果任务是相关的,为什么要使用 completableFuture

java - 期望这两个 CompletableFutures 得到相同的结果

java - 将 JSP 文件包含在另一个 JSP 文件中时出现 iFrame 浏览器问题

java - 借助组合框进行 JTable 选择?

java - 基于实体等于的唯一集的嵌套列表

java - 在 CompletableFuture 中多次运行 Runnable

Java8 CompletableFuture 条件链