如何等待runAsync完全完成可完成的将来?

问题描述 投票:0回答:1

此测试失败:

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及其所有附加子任务完成

java java.util.concurrent completable-future
1个回答
0
投票

在校对我的帖子时已解决:

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());
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.