首页 > 解决方案 > 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

标签: javalambda

解决方案


使用信号量可能是一种选择。但是如果由于某种原因至少有一个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();

推荐阅读