在我的主要流程中,我想并行执行一些任务。假设我有 4 个任务要在单独的流程中执行,但在这 4 个任务中,第一个任务需要先完成才能并行运行其他任务。
我认为我的代码符合我的要求,但是否有更好的方法?
public static void main(String[] args) {
System.out.println("In main");
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
runParalleltasks();
});
executor.shutdown();
System.out.println("Exiting main");
}
private static void runParalleltasks() {
System.out.println("Running parallel tasks");
doTask1();
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(() -> {
doTask2();
});
executor.submit(() -> {
doTask3();
});
executor.submit(() -> {
doTask4();
});
executor.shutdown();
System.out.println("Exiting parallel tasks");
}
最佳答案
您可能想看看新的 CompletableFuture
设施。对于像您这样的小案例,它可能不会提供很多帮助,但它提供了很大的灵 active :
import static java.util.concurrent.CompletableFuture.allOf;
import static java.util.concurrent.CompletableFuture.runAsync;
runAsync(() -> doTask1(), executor)
.thenCompose(v -> allOf(
runAsync(() -> doTask2(), executor),
runAsync(() -> doTask3(), executor),
runAsync(() -> doTask4(), executor)
));
如果您需要将 task1 的输出传递给从属任务,则此方法真正让您眼前一亮。假设 doTask1
返回一个 String
而 doTask2
接受一个 String
。现在我们应该使用 supplyAsync
而不是第一个任务的 runAsync
:
supplyAsync(() -> doTask1(), executor)
.thenCompose(resultOf1 -> allOf(
runAsync(() -> doTask2(resultOf1), executor),
runAsync(() -> doTask3(), executor),
runAsync(() -> doTask4(), executor)
));
关于java - 在并行运行其他线程之前等待第一个线程完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35790361/