如何 运行 执行列表中的服务并在 Java 中执行某些操作

How to run Executor Service on a list and perform some action in Java

我有一个项目列表,我想要 运行 执行程序服务来执行一些昂贵的操作:

var myList = Arrays.asList("item1", "item2");
var es = Executors.newFixedThreadPool(10);

myList.foreach(item -> {
    es.submit(() -> {
        performExpensiveAction(item);
    })
})

es.shutdown();

假设我在列表中有 100 个项目,我希望 es 对所有 100 个项目执行 performExpensiveAction,但它只对 10 个项目执行操作。

您应该考虑使用 invokeAll 而不是 shutdown.

The shutdown() method will allow previously submitted tasks to execute before terminating,

while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks.

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. (invokeAll waiting for all)

Documentation