如何同步两个异步任务? [英] How to synchronize two async task?

查看:162
本文介绍了如何同步两个异步任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

任务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?

推荐答案

如果这是Java-7你正在寻找对于 Phaser 。您需要的方法是到达和等待高级

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

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

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

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

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.

这篇关于如何同步两个异步任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆