Wait for multiple AsyncTask to complete

前端 未结 5 1033
自闭症患者
自闭症患者 2020-12-15 21:16

I am parallelizing my operation by splitting it in the exact number of cores available and then, by start the same number of AsyncTask, performing the same operation but on

5条回答
  •  心在旅途
    2020-12-15 22:11

    You could also simply decrement a counter in a shared object as part of onPostExecute. As onPostExecute runs on the same thread (the main thread), you won't have to worry about synchronization.

    UPDATE 1

    The shared object could look something like this:

    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"));
            }
        }
    }
    

    UPDATE 2

    According to the comments for this answer, OP is looking for a solution in which he can avoid building a new class. This can be done by sharing an AtomicInteger among the spawned AsyncTasks:

    // TODO Update type params according to your needs.
    public class MyAsyncTask extends AsyncTask {
        // 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"));    
            }
        }
    }
    

提交回复
热议问题