gpt4 book ai didi

concurrency - invokeAll() 是否停止主线程?

转载 作者:行者123 更新时间:2023-12-02 06:47:00 25 4
gpt4 key购买 nike

我想知道主线程是否会等到 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”。

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

最佳答案

这就是javadoc对于 invokeAll(...) 说(插入我的评论):

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() 返回之前,它说了 三次 任务已经完成。

关于concurrency - invokeAll() 是否停止主线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56846419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com