【问题标题】:Completion Callback in android thread poolandroid线程池中的完成回调
【发布时间】:2018-02-15 18:54:03
【问题描述】:

我开发了一个应用程序来读取点类型的 KML 文件,然后使用 Google Elevation API 更新它们的高程。如您所见,它接收点的纬度和经度,并将其附加一个 API 密钥以检索海拔。因为我的 KML 文件有多个点,所以我使用 ThreadPool 来读取点的纬度和经度,将其附加到密钥,然后将 URL 发送到 Google Elevation API。像这样:

ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(CORE_NUMBERS + 1);
    String providerURL = provider.getServiceURL();
    String providerKey =  provider.getServiceAPIkey();

for (PointFeature p: points) {

        String coordinate = p.getLatitude() + "," + p.getLongitude();       // get latitude and longitude of the feature
        String url = providerURL + "locations=" + coordinate + providerKey; // creating the url of web service which contains coordinate
        HeightTask task = new HeightTask(url, p);                           // task of each points            
        executor.execute(task);       
      }

heightTask 类是我从 API 解析 JSON 结果并获取高程并设置 heithUpdate 标志的地方。这是sn-p:

public class HeightTask implements Runnable {

private String url;    
private Feature feature;

public HeightTask(String url, Feature f) {

    this.feature = f;
    this.url = url;    
}

@Override
public void run() {

    if (feature instanceof PointFeature) {

        float height = GoogleAPIJsonParser.parsePoint(HttpManager.getData(url));
        if (height != Float.NaN){

            feature.updateHeight(height);
            feature.setHeightUpdated(true);
            Log.d("elevationPoint",height+"");
        }
    } 
}
}

我需要一个回调来了解图层中所有点的高程是否已更新。 threadPool 中是否有任何模式,或者只是遍历所有点并检查 hieghtUpdate 标志?

【问题讨论】:

    标签: android multithreading callback threadpool


    【解决方案1】:

    修改代码如下。

    1. 更改您的HeightTask 以实现Callable 接口。

    2. 准备一组Callable任务并使用invokeAll()提交

       List<HeightTask > futureList = new ArrayList<HeightTask >();
       for (PointFeature p: points) {
      
          String coordinate = p.getLatitude() + "," + p.getLongitude();       // get latitude and longitude of the feature
          String url = providerURL + "locations=" + coordinate + providerKey; // creating the url of web service which contains coordinate
          HeightTask task = new HeightTask(url, p);    
          futureList.add(taks);     
       }
       executor.invokeAll(futureList);
      

    调用全部:

    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
                           throws InterruptedException
    

    执行给定的任务,返回一个 Futures 列表,在所有完成后保存它们的状态和结果。 Future.isDone() 对于返回列表的每个元素都是 true。请注意,已完成的任务可能已经正常终止,也可能通过引发异常终止。

    【讨论】:

      猜你喜欢
      • 2015-04-06
      • 2015-08-29
      • 2010-10-16
      • 1970-01-01
      • 2011-06-02
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多