我有一个场景,我必须为同一个可调用对象异步执行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/