最近我深入研究了一些使用 API 的工作。 API 使用 Unirest http 库来简化从网络接收的工作。当然,由于数据是从 API 服务器调用的,因此我尝试通过对 API 的异步调用来提高效率。我的想法结构如下:
- 通过返回 future 结果创建数据数组
- 显示数据+从数据中收集的附加信息
因此,在开始第二步之前,我需要返回所有数据。我的代码如下:
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);
我如何做到只有在两个 future 都完成后才调用 doStuff?
最佳答案
有几个选项。您现在拥有的代码从发出请求的同一线程调用 doStuff
。如果您想阻塞直到两个请求都完成,您可以使用 CountDownLatch。像这样的东西:
CountDownLatch responseWaiter = new CountDownLatch(2);
Future <HttpResponse<JsonNode>> future1 = Unirest.get("https://example.com/api").asJsonAsync(new Callback<JsonNode>() {
public void completed(HttpResponse<JsonNode> response) {
responses.put(response);
responseWaiter.countDown();
}
...
});
// Similar code for the other get call
...
responseWaiter.await();
doStuff(responses);
如果您不想在两个调用完成之前阻塞该线程,您可以让每个匿名内部回调类递增一个 AtomicInteger。当计数为 2 时,您将调用 doStuff
。像这样的东西:
AtomicInteger numCompleted = new AtomicInteger();
Future <HttpResponse<JsonNode>> future1 = Unirest.get("https://example.com/api").asJsonAsync(new Callback<JsonNode>() {
public void completed(HttpResponse<JsonNode> response) {
responses.put(response);
int numDone = numCompleted.incrementAndGet();
if (numDone == 2) {
doStuff(responses);
}
}
});
关于java - 等待多个 future 的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20502394/