代码之家  ›  专栏  ›  技术社区  ›  arinte

为什么invokeAll()不返回?

  •  2
  • arinte  · 技术社区  · 16 年前

    我大致有以下代码:

    ExecutorService threader = Executors.newFixedThreadPool(queue.size());
    List futures = threader.invokeAll(queue);
    

    我调试这个并调用,直到队列中的所有线程都完成之后才返回。这一切发生的原因。

    3 回复  |  直到 12 年前
        1
  •  6
  •   Pete Kirkham    16 年前

    执行给定的任务,在所有任务完成时返回保持其状态和结果的期货列表。 the API

    你必须 submit() 而是一次一个,比如:

    public static <T> List<Future<T>> submitAll ( ExecutorService executor, Collection<? extends Callable<T> > tasks ) {
        List<Future<T>> result = new ArrayList<Future<T>>( tasks.size() );
    
        for ( Callable<T> task : tasks )
            result.add ( executor.submit ( task ) );
    
        return result;
    }
    
        2
  •  5
  •   Johannes Weiss    16 年前

    因为它的设计是这样的:

    [...]
    Executes the given tasks, returning a list of Futures holding their status and results when all complete. 
    [...]
    

    是来自 http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#invokeAll(java.util.Collection)

        3
  •  2
  •   Vikash    12 年前

    当我们呼唤 invokeAll() 它返回的方法 List<Futute<T>> 对象。 而这 Future 对象保留所有线程的值,直到成功执行为止。 所以当我们试图迭代 Future<T> 首先对其进行内部检查 Future<T>.isDone() [我们可以检查,也可以不检查 未来<t>.isdone() 外部的。如果返回true,我们可以遍历对象并访问 未来&科技; 对象,否则它将等待直到为真。

    注:如果 未来<t> 获取一个假对象,它不允许您遍历该对象。

    ExecutorService threader = Executors.newFixedThreadPool(queue.size());  
    List<Future<T>> listFuture = threader.invokeAll(queue);  
    for(Future<T> future: listFuture) {
        // Here you have the full access to this future object  
    }