此测试失败:
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/