【发布时间】: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