【问题标题】:How to wait for full completion of a completable future with runAsync?如何使用 runAsync 等待完全完成的未来?
【发布时间】:2019-10-20 21:28:22
【问题描述】:

此测试失败:

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】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-01-07
      • 2019-04-20
      • 1970-01-01
      • 2019-10-08
      • 2014-11-11
      • 1970-01-01
      • 2016-04-20
      • 1970-01-01
      • 2021-03-17
      相关资源
      最近更新 更多