如果两个不同的异步回调启动两个不同的同步方法会怎样?

时间:2018-07-09 14:11:30

标签: android asynchronous retrofit synchronous

假设我有两个不同的api(让api1和api2)。当api1的响应到达时,我调用了同步方法foo1()。同样,当api2的响应到达时,我调用了另一个同步方法foo2()。这是情况-我同时调用了两个API。 api1的响应到达,并调用方法foo1()。同时,来自api2的响应也到达,并且方法foo2()被调用。

我的问题是执行的顺序是什么? foo2()会等待foo1()完成还是会并行执行?

1 个答案:

答案 0 :(得分:0)

好吧,感谢@DroiDev,我自己尝试了一下。我将Anko library用于异步任务。下面是代码:

  doAsync {
        Log.d("ASYNC", "Async A started")
        foo1()
        uiThread {
            Log.d("ASYNC", "Async A done")
        }
    }

    Thread.sleep(1000)

    doAsync {
        Log.d("ASYNC", "Async B started")
        foo2()
        uiThread {
            Log.d("ASYNC", "Async B done")
        }
    }
}

fun foo1() {
    Log.d("ASYNC", "foo1() called")
    Thread.sleep(3000)
    Log.d("ASYNC", "foo1() done")
}

fun foo2() {
    Log.d("ASYNC", "foo2() called")
    Log.d("ASYNC", "foo2() done")
}

这是我得到的结果/日志:

07-12 11:44:55.195 23990-24054/gemini.com.jetpack D/ASYNC: Async A started
foo1() called
07-12 11:44:56.195 23990-24028/gemini.com.jetpack D/ASYNC: Async B started
foo2() called
07-12 11:44:56.205 23990-24028/gemini.com.jetpack D/ASYNC: foo2() done
07-12 11:44:56.215 23990-23990/gemini.com.jetpack D/ASYNC: Async B done
07-12 11:44:58.195 23990-24054/gemini.com.jetpack D/ASYNC: foo1() done
07-12 11:44:58.205 23990-23990/gemini.com.jetpack D/ASYNC: Async A done

因此,方法foo2()不会等待foo1()完成。