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