Android:等待几个异步任务完成

时间:2015-08-12 15:19:02

标签: java android multithreading android-asynctask

我必须多次调用才能将数据保存到我的数据库中。我必须等待所有的电话完成然后再进一步。我正在使用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。我可以知道我的代码中出了什么问题。

1 个答案:

答案 0 :(得分:1)

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

顺便说一下 - 你没有那里的线程和执行服务,你可以使用

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();

}