我有一个列表,其中包含我想用Android的DownloadManager下载的图像的URL。这是一个非常基本的设计,用于定义从列表中删除对象然后调用DownloadManager的AsyncTask子类。我的问题是如何处理AsyncTasks的并行性时,每个都将list.get(curentIndex)
。为了清楚起见,我希望每个任务(将在Executor上运行,因此在其他任务中运行,而不仅仅是主线程)以原子方式运行
将从列表中删除对象
将增加索引
答案 0 :(得分:1)
这通常是同步问题。有很多方法可以解决这个问题。我会建议一些事情:
// Your index. Defaulted at 0. Thread safe Integer wrapper object.
// All set/get operations are guaranteed atomical.
AtomicInteger mIndex = new AtomicInteger(0);
// Your list. This is thread-safe. All mutative operations
// are atomical, and properly locked. The list is copied on each write.
// This solution, though it does what it needs to do, is SLOW. Don't use for
// large lists.
CopyOnWriteArrayList<Object> mList = ... ;
// Your async task. Maybe more of them.
AsyncTask mTask = ...;
// Anything here that should be thread safe.
ensurePrerequisites(mTask);
// Execute on thread pool to make sure they're parallel.
// CAUTION: You will still get only (CPU_CORE_COUNT + 1) max parallel tasks.
mTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
public void synchronized ensurePrerequisites(AsyncTask task) {
// I assume you want to pass the values into the task.
int idx = mIndex.getAndIncrement();
task.setIndex(idx);
task.setObject(mList.remove(idx));
}