【发布时间】: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