4

作为异步编程的新手,我想知道我如何等待所有期货完成?

在我当前的用例中,我必须读取文件并使用 JSON 逐行将内容发布到 REST Web 服务。但是当我以正常方式执行此操作时,程序在所有期货完成之前就存在。

下面是该程序的一些代码。

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");
            }
        }
    );
}

此代码在所有期货完成之前运行并存在。关于我如何等待所有期货完成的任何提示?

4

1 回答 1

1

将所有这些 Future 放入集合中,例如 ArrayList。并得到他们所有。

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

    foreach(Future f : futures) f.get();
于 2015-04-04T08:56:56.087 回答