How to synchronize two async task?

2020-07-30 03:40发布

问题:

My problem is that I have two async tasks which doing a kind of matrix multiplications. Therefore both tasks are accessing the same matrix. One the upper part, the other the lower part. For memory saving issues I use ArrayLists and delete entries which I do not need longer. The problem is that in both tasks there is for loop runing and at the end of this loop it should wait for the other task. But I do not know how to do this. Task 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();
        }

Task 2:

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

I tried to use notify and wait, but it seems that this is not solving the issue. I do not know any additional methods which I could use to solve the issue. Is it actually possible to wait two for the other task while both are running?

回答1:

If this is Java-7 you are looking for a Phaser. The method you need is arriveAndAwaitAdvance.

In earlier versions of Java (5.1 or later) you would probably use a Semaphore.

Alternatively - you could switch to using a thread pool such as an ExecutorService and Futures. This would be much more scalable and take better advantage of the a multi-core processor.



回答2:

I believe the answer to questions below can provide you about the abstract information on how to manage multiple Async tasks.

How to manage multiple Async Tasks efficiently in Android

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

and github example:

https://github.com/vitkhudenko/test_asynctask (credits to: vitkhudenko)