java - Java - 等待 Lambda 完成后再继续
问题描述
我必须从 API 获取数据,所以很自然地我有一个端点处理程序,它通过一个 lambda 访问,我假设它产生了几个线程来完成我需要的每个 API 调用。但是,在完成所有 API 调用(所有 lambda 线程都完成)后,我需要整理我的数据。目前,我在主线程上运行的 Sort 方法因此在 lambda 中的任何 API 调用完成之前完成。这是我所拥有的样本
for(String data : dataArray) {
APIEndpoint apiCall = new APIEndpoint("http://sampleAPI.org/route/" + data);
apiCall.execute(((response, success) -> {
//Format and gather the info from the response
apiDataArray.add(DataFromAPIObject);
}));
}
System.out.print(apiDataArray.size());//Returns 0
sortData();//Currently Doesn't Sort anything because the array is empty
编辑:这是我正在使用的端点执行器: https ://github.com/orange-alliance/TOA-DataSync/blob/master/src/org/theorangealliance/datasync/util/FIRSTEndpoint.java
解决方案
使用信号量可能是一种选择。但是如果由于某种原因至少有一个data
点没有响应,它将陷入僵局。(要修复死锁,您可能需要在出现错误时释放信号量)。
Semaphore semaphore = new Semaphore(dataArray.length);
for (String data : dataArray) {
semaphore.acquire();
APIEndpoint apiCall = new APIEndpoint("http://sampleAPI.org/route/" + data);
apiCall.execute(((response, success) -> {
// Format and gather the info from the response
apiDataArray.add(DataFromAPIObject);
semaphore.release();
}));
}
semaphore.acquire(dataArray.length);
sortData();
推荐阅读
- kotlin - 我用 Ktor 编写了一个简单的反向代理,但发生错误:io.ktor.http.UnsafeHeaderException
- security - 如果我的服务仅在 K8 集群中被调用/公开,是否需要 HTTPS
- javascript - 如何阻止 npm 版本补丁格式化我的打字稿代码
- sql - 您如何更改 2019 SSRS 报告以打开 Chrome 浏览器而不是 Internet Explorer
- flutter - 使用用户配置文件进行颤振状态管理
- python - Python BeautifulSoup 从动态页面获取 html
- html - 如何根据css中的网页修复背景?
- c# - '无法加载文件或程序集'System.Windows,Version=5.0.5.0,Culture=neutral,PublicKeyToken=7cec85d7bea7798e'或其依赖项之一
- python - Pygsheets.authorize 每次运行时生成 tmp 文件
- swift - 在 Swift 上的应用程序后台运行任务