2015-04-04 158 views
2

作爲新來的異步編程,我想知道我是如何等待所有未來完成?如何等待所有異步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"); 
      } 
     } 
    ); 
} 

該代碼在所有期貨完成前運行並存在。有關我如何等待所有期貨完成的任何暗示?

+0

您是否找到了解決方案? – xro7 2016-11-09 11:33:22

回答

1

將所有這些期貨交給收款人,例如,數組列表。並把它們全部拿走。

List<Future> futures = ... 
// your while loop 

    foreach(Future f : futures) f.get();