【发布时间】:2020-08-04 03:06:28
【问题描述】:
//主线程在 Completable Future 中没有等待 Worker 线程完成。当我在 Completables 上运行 System.out.println 时,它们没有按顺序运行。
public class CompletableFutureMain {
public static void main(String[] args) {
System.out.println("Main Task : Thread Name=" + Thread.currentThread().getName());
CompletableFuture<String> stringCompletableFuture = null;
CompletableFuture<Integer> intCompletableFuture = null;
stringCompletableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println("Task 1 : Thread Name=" + Thread.currentThread().getName());
return getMeWelcomeMessage();
});
intCompletableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println("Task 2 : Thread Name=" + Thread.currentThread().getName());
return getMeARandomInteger();
});
System.out.println(stringCompletableFuture.get());
System.out.println(intCompletableFuture.get().toString());
}
private static String getMeWelcomeMessage() {
return "Trying Completable Future";
}
private static Integer getMeARandomInteger() {
return new Random().nextInt(100);
}
private static Double getMeARandomDouble() {
return new Random().nextDouble();
}
}
【问题讨论】:
-
为什么要按顺序运行?您已经启动了两个异步操作。这意味着不存在排序关系。等待与它有什么关系?当你在等车时,火车会改变它的时刻表吗?
标签: multithreading java-8 parallel-processing