【问题标题】:Hold calling thread until multiple asynctask finishes保持调用线程直到多个异步任务完成
【发布时间】:2016-12-09 02:51:02
【问题描述】:

我有一个后台线程,它调用 3 个异步任务来同时执行任务。调用线程充当 3 组这些任务的队列。

所以基本上我需要同时调用 3 个异步任务,一旦它们完成,我想调用队列中接下来的三个任务并重复。

但是,在三个异步任务完成之前,我无法暂停调用者线程。因此,队列中的下三个任务在前三个任务完成之前开始运行。

所以无论如何都要在异步任务完成之前保持调用者线程。我知道你可以在 asynctask 中使用 .get() 但它不会使三个 asynctasks 同时运行。

【问题讨论】:

  • 也许这可以通过将侦听器传递给您的 3 asynctask 并在您的 3 asynctask 的 onPostExecute 中调用您的侦听器的方法来完成,当 3 asynctask 调用此方法时,您可以启动您的 3 next asynctask .而且我认为您应该使用服务而不是线程来启动您的异步任务。希望有所帮助。
  • 我正在使用 looper 对任务进行排队,因此我找不到暂停调用下一个任务的方法。
  • 如果我没记错的话,Looper 不是用来暂停的。如果我必须做类似的事情,我会通过服务获取您的任务列表(可以动态设置)并在同一时间启动 3 个任务,然后当它们完成时重新启动 startComand,而您在队列中有任务或类似的东西.

标签: android android-asynctask android-handler android-looper


【解决方案1】:

异步任务是为了异步执行任务......所以这不能直接完成......

即使你设法做到这一点,它也基本上破坏了异步操作的全部意义。

您应该寻找同步网络操作。

查看Volley...这是一个专门为网络操作而制作的google库,它支持同步操作

http://www.truiton.com/2015/02/android-volley-making-synchronous-request/

还有许多其他可用的库...Retrofit 是另一个不错的库..

【讨论】:

  • 我也需要异步功能,但一次只需要三个
【解决方案2】:

以下代码是该想法的伪代码。基本上,您将声明一个接口,该接口将检查触发接下来的三个 AsyncTask。您还需要维护一个计数器来查看从 AsyncTask 接收到的响应数是否乘以 3。如果是,那么您可以触发接下来的三个 AsyncTask。

public interface OnRunNextThree{
     void runNextThreeTasks();
}

public class MainClass extends Activity implements OnRunNextThree {

    private int asyncTasksCounter = 0;

    public void onCreate() {
        //Initiate and run first three of your DownloadFilesTask AsyncTasks

        // ...
    }

    public void runNextThreeTasks() {
        if (asyncTasksCounter % 3 == 0) {
            // you can execute next three of your DownloadFilesTask AsyncTasks now

            // ...
        } else {
            // Otherwise, since we have got response from one of our previously 
            // initiated AsyncTasks so let's update the counter value by one. 
            asyncTasksCounter++;
        }
    }

    private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {

        private OnRunNextThree onRunNextThree;

        public DownloadFilesTask(OnRunNextThree onRunNextThree) {
            this.onRunNextThree = onRunNextThree;
        }


        protected Void doInBackground(Void... voids) {
            // Do whatever you need to do in background
            return null;
        }

        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            //Got the result. Great! Now trigger the interface.
            this.onRunNextThree.runNextThreeTasks();
        }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 2018-10-08
    • 2013-12-12
    • 1970-01-01
    • 2021-10-13
    • 2018-10-10
    • 2016-05-31
    相关资源
    最近更新 更多