gpt4 book ai didi

java - 等待多个 AsyncTask 完成

转载 作者:搜寻专家 更新时间:2023-10-30 19:42:29 26 4
gpt4 key购买 nike

我通过将操作拆分为确切数量的可用内核来并行化我的操作,然后启动相同数量的 AsyncTask,执行相同的操作,但对数据的不同部分执行。

我正在使用 executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, ...) 以并行执行它们。

我想知道每个线程何时完成其工作,以便合并所有结果并执行进一步的操作。

我该怎么办?

最佳答案

作为 onPostExecute 的一部分,您还可以简单地减少共享对象中的计数器。由于 onPostExecute 在同一个线程(主线程)上运行,您不必担心同步问题。

更新 1

共享对象看起来像这样:

public class WorkCounter {
private int runningTasks;
private final Context ctx;

public WorkCounter(int numberOfTasks, Context ctx) {
this.runningTasks = numberOfTasks;
this.ctx = ctx;
}
// Only call this in onPostExecute! (or add synchronized to method declaration)
public void taskFinished() {
if (--runningTasks == 0) {
LocalBroadcastManager mgr = LocalBroadcastManager.getInstance(this.ctx);
mgr.sendBroadcast(new Intent("all_tasks_have_finished"));
}
}
}

更新 2

根据这个答案的评论,OP 正在寻找一种解决方案,他可以在其中避免构建新类。这可以通过在派生的 AsyncTask 之间共享一个 AtomicInteger 来完成:

// TODO Update type params according to your needs.
public class MyAsyncTask extends AsyncTask<Void,Void,Void> {
// This instance should be created before creating your async tasks.
// Its start count should be equal to the number of async tasks that you will spawn.
// It is important that the same AtomicInteger is supplied to all the spawned async tasks such that they share the same work counter.
private final AtomicInteger workCounter;

public MyAsyncTask(AtomicInteger workCounter) {
this.workCounter = workCounter;
}

// TODO implement doInBackground

@Override
public void onPostExecute(Void result) {
// Job is done, decrement the work counter.
int tasksLeft = this.workCounter.decrementAndGet();
// If the count has reached zero, all async tasks have finished.
if (tasksLeft == 0) {
// Make activity aware by sending a broadcast.
LocalBroadcastManager mgr = LocalBroadcastManager.getInstance(this.ctx);
mgr.sendBroadcast(new Intent("all_tasks_have_finished"));
}
}
}

关于java - 等待多个 AsyncTask 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32625599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com