【问题标题】:How to wait for all async REST calls are finished using Unirest?如何使用 Unirest 等待所有异步 REST 调用完成?
【发布时间】:2015-06-09 05:57:30
【问题描述】:

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

在我当前的用例中,我必须读取文件并使用 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");
            }
        }
    );
}

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

【问题讨论】:

  • 您找到解决方案了吗?

标签: java rest asynchronous unirest


【解决方案1】:

将所有这些 Future 放入集合中,例如数组列表。把它们都拿走。

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

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

【讨论】:

    猜你喜欢
    • 2011-10-04
    • 2016-03-16
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多