异步调用两个Java方法

use*_*180 1 java multithreading asynchronous

我有以下代码正在调用两个Web服务。这两个Web服务都返回非常大的响应,因此响应要花相当长的时间(一个Web服务请求为8秒,另一个为12秒)。由于请求是串行而不是并行运行的,因此总执行时间为20秒。

有什么方法可以修改我的代码以异步请求两个Web服务,并且能够在比当前花费的20秒更短的12秒时间内处理响应?

String listOfCities;
String listOfCountries; 

try {
    listOfCities = service.getListOfCities(host+"service/cities");
    listOfCountries = service.getListOfCountries(host+"service/countries");
} catch (Exception e) {
    log.error("Failed to read service: " + e);
}
Run Code Online (Sandbox Code Playgroud)

**感谢您的答复,我觉得这不是重复的,因为我想停止执行我正在执行的两个线程,直到两个线程都收到了结果。下面的解决方案表明了这一点。**

Sar*_*cht 5

非常简单的实现,有关更多信息,您可能需要看一下FutureTask

    List<Thread> threadList = new ArrayList<>();
    threadList.add(new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                listOfCountries = service.getListOfCountries(host+"service/countries");
            } catch (Exception e) {
                log.error("Failed to read service: " + e);
            }
        }
    }));
    threadList.add(new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                listOfCities = service.getListOfCities(host+"service/cities");
            } catch (Exception e) {
                log.error("Failed to read service: " + e);
            }
        }
    }));
    for (Thread t:threadList ){
        t.start();
    }
    for (Thread t:threadList ){
        try {
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    //after both finish proceeds from here
Run Code Online (Sandbox Code Playgroud)

请注意,应该更全局地定义字符串(类级别,而不是局部变量)


esi*_*n88 5

我会尝试一些简单的方法,例如CompletableFuture

import java.util.concurrent.CompletableFuture;
...
final CompletableFuture<String> listOfCities = CompletableFuture.supplyAsync(() -> service.getListOfCities(...));
final CompletableFuture<String> listOfCountries = CompletableFuture.supplyAsync(() -> service. getListOfCountries(...));
final CompletableFuture<Void> allCompleted = CompletableFuture.allOf(listOfCities, listOfCountries);
allCompleted.thenRun(() -> {
    // whatever you want to do 
});
Run Code Online (Sandbox Code Playgroud)

请参阅这些示例以供参考。