8
最近我已經鑽研使用API的一些工作。該API使用Unirest http庫來簡化從網絡接收的工作。當然,由於數據是從API服務器調用的,我試圖通過對API進行異步調用來提高效率。我的想法的結構如下:等待多個期貨的回調
- 通過返回期貨從數據
因此聚集
Future < HttpResponse <JsonNode> > future1 = Unirest.get("https://example.com/api").asJsonAsync(new Callback <JsonNode>() {
public void failed(UnirestException e) {
System.out.println("The request has failed");
}
public void completed(HttpResponse <JsonNode> response) {
System.out.println(response.getBody().toString());
responses.put(response);
}
public void cancelled() {
System.out.println("The request has been cancelled");
}
});
Future < HttpResponse <JsonNode> > future2 = Unirest.get("https://example.com/api").asJsonAsync(new Callback <JsonNode>() {
public void failed(UnirestException e) {
System.out.println("The request has failed");
}
public void completed(HttpResponse <JsonNode> response) {
System.out.println(response.getBody().toString());
responses.put(response);
}
public void cancelled() {
System.out.println("The request has been cancelled");
}
});
doStuff(responses);
我該如何做到這一點,所以doStuff只有在兩個期貨完成後纔會被調用?
可能想看看'ExecutorCompletionService'但允許您在任何響應完成做的東西。 – Gray
http://stackoverflow.com/questions/3269445/executorservice-how-to-wait-for-all-tasks-to-finish – goat