1

我有一个包含纬度和经度值的列表,我只是遍历此列表以获取纬度和经度,并找到特定纬度和经度的天气报告,并以 dB 为单位更新天气报告,但 100 次大约需要 75 秒。我怎样才能减少这个时间?

ExecutorService executor=Executors.newFixedThreadPool(10);

HttpClient weatherClient=new DefaultHttpClient();
for(LatandlngList value:latandlngList)
{
   Double lat= value.getLat();
   Double lng= value.getLng();
   String URL="http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lng="+lng
             +"&appid="+appId;

Future<String>future=executor. Submit(() - >findWeatherReport(URL) ;
Updateweatherreport(future.get());


}

private String findWeatherReport(URL){
HttpGet weatherReq=new HttpGet(URL);
HttpResponse weatherresult=weatherClient.execute(weatherReq);
return weatherresult;
} 

Private String Updateweatherreport(weatherreport)
{
//code for update weather report in dB 
return "ok" ;
} 
4

1 回答 1

1

而不是你现在正在做的事情

Future<String>future=executor. Submit(() - >findWeatherReport(URL) ;
Updateweatherreport(future.get());

创建一个同时执行的方法并调用它。

private String findAndUpdateWeatherReport(String url) {
  String report = findWeatherReport(url);
  return Updateweatherreport(report);
}

现在在调用代码中

executor.submit(() -> findAndUpdateWeatherReport(URL));

然后在提交后执行以下操作

executor.shutdown();
while (!executor.awaitTermination(500, TimeUnit.MILLISECONDS)) {}

这将关闭执行器并等待所有任务完成,然后清理执行器。

于 2021-11-10T08:48:18.980 回答