【问题标题】:Android: wait for several Async Tasks to completeAndroid:等待几个异步任务完成
【发布时间】:2015-08-12 15:19:01
【问题描述】:

我必须多次调用才能将数据保存到我的数据库中。我必须等待所有呼叫完成,然后再继续前进。我正在使用 CountDownLatch 和 ExecutorService 来实现这一点。以下是我的代码:

    private void saveData(double latitude, double longitude) {
    try {
        performParallelTask(getListOfLatLngPair(latitude, longitude));
        preformPostTask();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public void performParallelTask(List<LatLngPair> latLngPairList) throws InterruptedException {
    CountDownLatch doneLatch = new CountDownLatch(latLngPairList.size());
    ExecutorService executorService = Executors.newFixedThreadPool(latLngPairList.size());
    for (int i = 0; i < latLngPairList.size(); i++) {
        executorService.execute(new StopLatchedThread(doneLatch, latLngPairList.get(i)));
    }
    doneLatch.await();
}

public class StopLatchedThread implements Runnable {
    private final CountDownLatch stopLatch;
    private final LatLngPair latLngpair;

    public StopLatchedThread(CountDownLatch stopLatch, Fence latLngpair
                            ) {
        this.stopLatch = stopLatch;
        this.latLngpair = latLngpair;
    }

    public void run() {
        try {
            addLatLngPair();
        } finally {
            stopLatch.countDown();
        }
    }

    private void addLatLngPair() {
        Log.i(LOG_AREA, "add fence method");
        Engine.AddLatLngPair(latLngPair, new Engine
            .LatLngPairOperationListener() {
            @Override
            public void Succeed() {
                // do noting
            }

            @Override
            public void Failed(int reason) {
                Log.i(LOG_AREA, "Failed to add pair"
            }
        });
    }
}

private void preformPostTask() {
    Intent intent = new Intent(PairListActivity.this, PairListMapActivity.class);
    atartActivity(intent);
}

当我尝试执行代码时,它会在线程完成执行之前启动 Activity。我可以知道我的代码有什么问题吗?

【问题讨论】:

  • 问题出在哪里?
  • @Nambari 我编辑了我的问题

标签: java android multithreading android-asynctask


【解决方案1】:

我坚信 Engine.AddLatLngPair 是一个异步调用,因此您必须在 _Succeed()_ 和 _Failed(int reason)_ 方法中调用 stopLatch.countDown();

顺便说一句 - 你没有线程和执行器服务,你可以使用

public void performParallelTask(List<LatLngPair> latLngPairList) throws InterruptedException {
CountDownLatch doneLatch = new CountDownLatch(latLngPairList.size());
for (int i = 0; i < latLngPairList.size(); i++) {
    addLatLngPair(doneLatch, latLngPairList.get(i));
}
doneLatch.await();

}

【讨论】:

  • 是的。 Engine.LatLngPair 是异步调用。那我应该移动 stopLatch.countDown();成功和失败的方法,我完成了吗?
  • 我认为它应该可以解决问题。试一试,如果它不起作用,请告诉我。
猜你喜欢
  • 1970-01-01
  • 2013-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多