我编写了一个将任务提交给 ExecutorService 的函数。该函数有一个条件,如果为真,函数将调用自身来创建另一个任务。
private void taskCreator(int v, ExecutorService executor) {
executor.submit(() -> {
if (// some condition) {
taskCreator(u, executor);
}
});
}
如何才能等到所有任务完成?
我尝试将Future与方法get()一起使用,但主线程在ExecutorService之前完成执行。我也不知道会有多少任务。
比如这样
public class ExecutorServiceDemo {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService service = Executors.newFixedThreadPool(10);
try {
List<Future<?>> futures = new ArrayList<>();
for (int index = 0; index < 100; index++) {
final int number = index;
futures.add(service.submit(() -> {
try {
System.out.println("Task " + number + " startup");
Thread.sleep(1000);
System.out.println("Task " + number + " shutdown");
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
}
}));
}
// Wait for all threads to finish
for (Future<?> future : futures) {
future.get();
}
} finally {
service.shutdown();
if (!service.awaitTermination(10, java.util.concurrent.TimeUnit.SECONDS)) {
service.shutdownNow();
}
}
}
}