gpt4 book ai didi

java - 是使用invokeAll还是提交-Java Executor服务

转载 作者:行者123 更新时间:2023-12-01 07:43:02 26 4
gpt4 key购买 nike

我有一个场景,我必须为同一个可调用对象异步执行5个线程。据我了解,有两种选择:

1)使用submit(Callable)

ExecutorService executorService = Executors.newFixedThreadPool(5);
List<Future<String>> futures = new ArrayList<>();
for(Callable callableItem: myCallableList){
futures.add(executorService.submit(callableItem));
}

2)使用invokeAll(Callable的集合)
ExecutorService executorService = Executors.newFixedThreadPool(5);
List<Future<String>> futures = executorService.invokeAll(myCallableList));
  • 应该首选哪种方式?
  • 与另一个相比,它们中的任何一个都有不利之处或对性能的影响吗?
  • 最佳答案

    选项1 :您正在将任务提交给ExecutorService,并且您不等待已提交给ExecutorService的所有任务的完成。

    选项2 :您正在等待所有已提交给ExecutorService的任务的完成。

    What should be the preferred way?



    根据应用需求,它们中的任何一个都是优选的。
  • 如果您不想在对ExecutorService进行任务commit()之后等待,请首选Option 1
  • 如果您需要等待已提交给ExecutorService的所有任务完成,请使用Option 2

  • Is there any disadvantage or performance impact in any of them compared to the other one?



    如果您的应用程序需要选项2,则与选项1不同,您必须等待提交给 ExecutorService的所有任务的完成。性能不是进行比较的标准,因为两者都是为两个不同的目的而设计的。

    还有一件重要的事情:无论您选择哪种选项, FutureTask都会在任务执行过程中吞下异常。你必须要小心。看看这个SE问题: Handling Exceptions for ThreadPoolExecutor

    使用Java 8,您还有一个选择: ExecutorCompletionService

    A CompletionService that uses a supplied Executor to execute tasks. This class arranges that submitted tasks are, upon completion, placed on a queue accessible using take. The class is lightweight enough to be suitable for transient use when processing groups of tasks.



    看看相关的SE问题: ExecutorCompletionService? Why do need one if we have invokeAll?

    关于java - 是使用invokeAll还是提交-Java Executor服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34440604/

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