invokeAll() 是否停止主线程?

Does invokeAll() stop the main Thread?

我想知道主线程是否会等到 invokeAll() 参数中的所有任务完成后才继续。这是我的代码,它似乎确实如此。

public static void main(String[] args) throws InterruptedException {

    ExecutorService service = null;
    try
    {
        service = Executors.newCachedThreadPool();
        List<Callable<?>> list = new ArrayList<>();
        for(int i = 0; i < 1000; i++)
        {
            list.add(() -> {System.out.println("Not yet"); return null;});
        }
        service.invokeAll(list);
        System.out.println("END!"); // Output "END" at last no matter what
    }
    finally
    {
        if(service != null)
        {
            service.shutdown();
        }
    }
}

如你所见,无论我创建了多少个任务,无论是1000个还是10000个,程序最后还是输出了"END"

谁能证实这个信息?非常感谢!

ExecutorService.invokeAll() 文档指出(重点是我的):

Executes the given tasks, returning a list of Futures holding their status and results when all complete.

并且 ExecutorService class documentation 为设计用于 运行 任务的每个方法强调了这一点(重点是我的):

Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete.

至少一个用于invokeAny()所有用于invokeAll().

invokeAll(...)javadoc 是这么说的(插入了我的评论):

Executes the given tasks, returning a list of Futures holding their status and results when all complete.

注意:“全部完成时”……不是之前。

Future.isDone() is true for each element of the returned list.

这意味着任务已经完成。

Note that a completed task could have terminated either normally or by throwing an exception. The results of this method are undefined if the given collection is modified while this operation is in progress.

Parameters: tasks - the collection of tasks

Returns: A list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task list, each of which has completed.

再次......它说任务已经完成。


简而言之,在 invokeAll() returns.

之前,任务已经完成 三次