java - Java中 future 的相关澄清

标签 java executorservice threadpoolexecutor java-threads

我的应用程序中有以下方法,它看起来工作正常..但我不确定它是如何...

ArrayList arr = new ArrayList();
Collection<Future<?>> futures = new LinkedList<Future<?>>();
RestCallThread thread = null;
HttpHeaders header = getAuthHeader(authorization);
for (String ids : IDS) {
    thread = new RestCallThread(ids, header);
    futures.add(executor.submit(thread));
}

for (Future<?> future : futures) {
    try {
        arr.add(future.get());
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
}
return arr;

在代码中,RestAPI调用被添加到ThreadPoolExecutor并等待结果..

我的问题是,由于该方法是基于线程的,因此如何在所有 API 线程完成之前不执行 return 语句...

return 语句有可能返回空列表吗?

最佳答案

My Question is Since the approach is based on thread how the return statement is not executed till all the API threads get completed...

阅读有关 Future#get() 的 JavaDoc:

Waits if necessary for the computation to complete, and then retrieves its result.

这意味着循环将被阻塞,直到当前迭代的 future 得到其结果,即当循环完成时,您知道所有线程都已完成。

Any chance of return statement will return empty list?

是的,例如如果IDS为空或者所有线程都因异常而失败。

关于java - Java中 future 的相关澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37811370/

相关文章:

Java并行多个任务超时

java - 如何从 future 对象中查看执行了哪个线程(名称)

java - 为什么 ThreadPoolExecutor 的 afterExecute() 异常为 null?

java - JAVA中唯一标识终止的线程

java - 仅检索 POST 参数 (Java)

声明日志文件路径时出现 java.io.IOException

java - Executors.newFixedThreadPool 如何停止同步方法上的所有 Activity 线程

java - 使用 Executor 处理 10000 个线程

java - 为什么 2010 年 12 月 31 日返回 1 作为一年中的一周?

java - 如何从连接表中为每个主键项仅选择一条记录?