簡體   English   中英

Java-等待Lambda完成后再繼續

[英]Java - Wait for Lambda to Finish before continuing

我必須從API獲取數據,所以自然地,我有一個通過lambda訪問的終結點處理程序,我假設該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

編輯:這是我正在使用的Endpoint Executer: 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM