Java 如何使用Unirest并行发送多个异步请求

Java 如何使用Unirest并行发送多个异步请求,java,multithreading,asynchronous,unirest,Java,Multithreading,Asynchronous,Unirest,在使用Unirest时,只有通过调用Unirest.shutdown()手动关闭每个线程,程序才会退出。如果我只需要提出一个请求,那很容易: private static void asyncRequest (String link) { try { Future <HttpResponse <JsonNode>> request = Unirest.head(link).asJsonAsync( new Callb

在使用Unirest时,只有通过调用
Unirest.shutdown()
手动关闭每个线程,程序才会退出。如果我只需要提出一个请求,那很容易:

private static void asyncRequest (String link) {
    try {
        Future <HttpResponse <JsonNode>> request = Unirest.head(link).asJsonAsync(
                new Callback<JsonNode>() {
                    @Override
                    public void completed(HttpResponse<JsonNode> httpResponse) {
                        print(httpResponse.getHeaders());
                        try {
                            Unirest.shutdown();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(UnirestException e) {
                        print(e.getMessage());
                    }

                    @Override
                    public void cancelled() {
                        print("Request cancelled");
                    }
                }
        );

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) throws Exception {
   asyncRequest("https://entrepreneur.com");
}
私有静态无效异步请求(字符串链接){
试一试{
未来请求=Unirest.head(link.asJsonAsync(
新回调函数(){
@凌驾
公共无效已完成(HttpResponse HttpResponse){
打印(httpResponse.getHeaders());
试一试{
Unirest.shutdown();
}捕获(IOE异常){
e、 printStackTrace();
}
}
@凌驾
public void失败(unireste异常){
打印(如getMessage());
}
@凌驾
公众假期取消(){
打印(“取消请求”);
}
}
);
}捕获(例外e){
e、 printStackTrace();
}
}
公共静态void main(字符串[]args)引发异常{
异步请求(“https://entrepreneur.com");
}

但我必须并行地发出多个HTTP请求(后续请求意味着不要等待前面的请求完成)。在上面的代码中,我必须使用不同的
link
s多次执行
asyncRequest
中的代码。问题是我无法决定何时调用
Unirest.shutdown()
,以便程序在最后一个请求收到响应时立即退出。如果在
main
中对
asyncRequest
的所有调用之后调用
Unirest.shutdown()
,则可能会中断部分或所有请求。如果我在
completed
(和其他重写的方法)中调用它,则只会发出第一个请求,而其他请求会被中断。如何解决这个问题?

理论上,您可以让当前线程等待方法的执行,并且在完成所有操作后,可以调用shutdown。但这将使整个过程同步,这不是我们想要的。所以我要做的是,运行不同的线程(主线程除外),它将等待所有http请求的执行。为此,您可以使用类
CountDownLatch
,在将控件释放到父线程之前使用倒计时进行初始化。将
CountDownLatch
的实例传递给
async
方法,并在每次完成http请求时将
减少一个
。当它达到0时,它将控件返回到父线程,您知道在所有请求完成时可以调用
shutdown
方法