如何同步两个异步任务?

时间:2013-09-20 10:02:38

标签: java android multithreading asynchronous android-asynctask

我的问题是我有两个执行一种矩阵乘法的异步任务。因此,两个任务都访问相同的矩阵。一个是上部,另一个是下部。对于内存保存问题,我使用ArrayLists并删除不再需要的条目。问题是,在这两个任务中都存在循环运行,并且在该循环结束时它应该等待另一个任务。但我不知道该怎么做。 任务1:

protected Void doInBackground(Void... paramArrayOfParams) {
        android.os.Debug.waitForDebugger();
        for(j=1; j<(size+1); j++)
        {
            .... 
            try{ othertask.wait();
            }catch(InterruptedException e){}
            //wait for other task();
        }

任务2:

protected Void doInBackground(Void... paramArrayOfParams) {
            android.os.Debug.waitForDebugger();
            for(j=1; j<(size+1); j++)
            {
                ....
                notifyAll();
                //notifythatroundisfinished();
            }

我尝试使用通知并等待,但似乎这并没有解决问题。我不知道可以用来解决问题的任何其他方法。实际上,当两个任务都在运行时,是否可以等待两个任务?

2 个答案:

答案 0 :(得分:1)

我相信以下问题的答案可以为您提供有关如何管理多个异步任务的抽象信息。

How to manage multiple Async Tasks efficiently in Android

Running multiple AsyncTasks at the same time -- not possible?

和github示例:

https://github.com/vitkhudenko/test_asynctask(来自:vitkhudenko)

答案 1 :(得分:0)

如果这是Java-7,那么您正在寻找Phaser。您需要的方法是arriveAndAwaitAdvance

在早期版本的Java(5.1或更高版本)中,您可能会使用Semaphore

或者 - 您可以切换到使用线程池,例如ExecutorServiceFutures。这将更具可扩展性,并且可以更好地利用多核处理器。