【问题标题】:Difference between Executor and ExecutorCompletionservice in javajava中Executor和ExecutorCompletionservice的区别
【发布时间】:2011-12-07 03:58:30
【问题描述】:

正如问题标题本身所说,java中的Executors和ExecutorCompletionService类有什么区别?

我是线程新手,所以如果有人能用一段代码解释一下,那将有很大帮助。

【问题讨论】:

    标签: java multithreading java.util.concurrent


    【解决方案1】:

    假设您有一组任务 A, B, C, D, E,并且您希望在 Executor 中异步执行每个任务,并在它们完成时逐一处理结果。

    使用Executor,您可以这样做:

    List<Future<?>> futures = new ArrayList<Future<?>>();
    futures.add(executorService.submit(A));
    futures.add(executorService.submit(B));
    futures.add(executorService.submit(C));
    futures.add(executorService.submit(D));
    futures.add(executorService.submit(E));
    
    //This loop must process the tasks in the order they were submitted: A, B, C, D, E
    for (Future<?> future:futures) {
        ? result = future.get();
        // Some processing here
    }
    

    这种方法的问题是不能保证任务A会先完成。因此,当主线程可能正在处理另一个任务的结果(比如任务B)时,它可能会空闲地阻塞等待任务A 完成。使用ExecutorCompletionService 可以减少结果处理延迟。

    List<Future<?>> futures = new ArrayList<Future<?>>();
    futures.add(executorCompletionService.submit(A));
    futures.add(executorCompletionService.submit(B));
    futures.add(executorCompletionService.submit(C));
    futures.add(executorCompletionService.submit(D));
    futures.add(executorCompletionService.submit(E));
    
    //This for loop will process the tasks in the order they are completed,  
    //regardless of submission order
    for (int i=0; i<futures.size(); i++) {
        ? result = executorCompletionService.take().get();
        // Some processing here
    }
    

    所以,本质上,ExecutorCompletionService 可以用来在处理任务结果的顺序无关紧要的情况下挤出一点效率。

    有一点需要注意。 ExecutorCompletionService 的实现包含一个结果队列。如果没有调用takepoll 来排空该队列,则会发生内存泄漏。有些人使用submit返回的Future来处理结果,这是不正确的用法。

    【讨论】:

    • 非常感谢蒂姆的支持。示例和解释非常清楚。
    • 这样一个惊人的答案,到目前为止只有 18 票。这让我很难过。那个婴儿在你手中看起来很可爱。
    【解决方案2】:

    ExecutorCompletionService 将简单地包装并委托给普通的Executor,并提供方便的方法来检索最近完成的任务。

    该 api 有一些示例可以帮助您进行操作

    http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorCompletionService.html

    【讨论】:

      猜你喜欢
      • 2012-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-21
      • 1970-01-01
      • 2014-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多