简体   繁体   English

如何有效处理执行人服务的多个结果

[英]How do I efficiently process multiple results from an Executor Service

I'n new to ExecutorService, but am unsure about my approach to this. 我不是ExecutorService的新手,但是不确定我的处理方法。 I could be dealing with up to 100 threads for a known task. 我可能要为一个已知任务处理多达100个线程。 I'm using the general format below, where I create a List of FutureTasks, then submit these to the ExecutorService. 我使用下面的常规格式,在其中创建FutureTasks列表,然后将其提交到ExecutorService。 The ExecutorService returns and adds these pending results to another list. ExecutorService返回并将这些挂起的结果添加到另一个列表中。 I then iterate over this list, calling get() on each pending result. 然后,我遍历此列表,对每个挂起的结果调用get()。

My query is : won't this block on each get() in turn until all 100 threads have completed ? 我的查询是:直到所有100个线程都完成后,才会在每个get()上依次阻止此块吗? Is there a better way to do this ? 有一个更好的方法吗 ?

And am I right in assuming that get() returns the result of the Callable implementation's call() method ? 我是否正确假设get()返回Callable实现的call()方法的结果? I'm using the default FutureTask class, and haven't subclassed it. 我正在使用默认的FutureTask类,并且尚未对其进行子类化。

ExecutorService exec = Executors.newFixedThreadPool( NUM_THREADS );

List<JobClass> originalList = new ArrayList<JobClass>();

List<SomeOtherClass> pendingResult = new ArrayList<SomeOtherClass>();

List<Future<SomeOtherClass>> resultList = new ArrayList<Future<SomeOtherClass>>();

for( JobClass sc : originalList )
    pendingResult.add( submit( sc );

for( Future<SomeOtherClass> future : futures )
    resultList.add( future.get(5, TimeUnit.SECONDS) ); 

Good question, if I understand you correctly, you are worried about consumption of the result of completed tasks. 很好的问题,如果我对您的理解正确,那么您将担心消耗已完成任务的结果。 Yes the thread will block. 是的,线程将阻塞。 Java's answer to that is using the CompletionService . Java的答案是使用CompletionService

As mentioned in the documentation page "A service that decouples the production of new asynchronous tasks from the consumption of the results of completed tasks". 如文档页面中所述:“将新异步任务的产生与完成任务的结果消耗分开的服务”。

If you only proceed if all tasks are completed, you can do what you suggested. 如果仅在所有任务完成后继续进行,则可以执行建议的操作。 It will not matter in which order tasks complete. 任务的完成顺序无关紧要。 However, if you need to pass task results to other processor as soon as possible or do something else while tasks are executing, you may want to check if task is complete first using isDone method, for example, and call get() if it is complete. 但是,如果您需要尽快将任务结果传递给其他处理器,或者在执行任务时执行其他操作,则可能需要首先使用isDone方法检查任务是否完成,如果是,则调用get()完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM