如何等待所有异步REST调用使用Unirest完成?
问题描述:
作为新来的异步编程,我想知道我是如何等待所有未来完成?如何等待所有异步REST调用使用Unirest完成?
在我目前的使用情况下,我必须读取一个文件并将内容逐行使用JSON发布到REST Webservice。但是,当我以正常的方式执行此程序时,该程序在所有期货完成之前就已存在。
下面是程序的一些代码。
while ((line = br.readLine()) != null) {
Future<HttpResponse<String>> future = Unirest.post("http://www.dummy.net")
.fields(map)
.asStringAsync(new Callback<String>() {
public void completed(HttpResponse<String> response) {
int code = response.getStatus();
}
public void failed(UnirestException e) {
System.out.println("The request has failed");
}
public void cancelled() {
System.out.println("The request has been cancelled");
}
}
);
}
该代码在所有期货完成前运行并存在。有关我如何等待所有期货完成的任何暗示?
答
将所有这些期货交给收款人,例如,数组列表。并把它们全部拿走。
List<Future> futures = ...
// your while loop
foreach(Future f : futures) f.get();
您是否找到了解决方案? – xro7 2016-11-09 11:33:22