协程的哪个组件执行挂起函数

问题描述 投票:0回答:1

我最近试图找出谁真正负责执行挂起函数 所以 我在我的协程中创建了一些挂起函数

fun main(args: Array<String>) {

for (x in 1..20){
    CoroutineScope(Dispatchers.Default).launch{
        for (i in 1..5) {
            if(i % 2 == 0){
                myFun(i, Thread.currentThread().name)
            }else{
                myFun2(i, Thread.currentThread().name)
            }
        }
    }
}


Thread.sleep(3000000)  //this is just to wait for all coroutines to complete, ignore it

}

suspend fun myFun(n : Int, tName : String) {
    println("myFun method called from Thread = $tName, for i = $n")
    println("myFun -> executing on Thread = ${Thread.currentThread().name}, came from Thread = $tName")
    delay(1000)
    val x = n * n;
    println("myFun -> performing square operation on Thread = ${Thread.currentThread().name}, for i = $n came from Thread = $tName")

    myFun3(x, Thread.currentThread().name, tName);
    println("myFun method finished for i = $n, on Thread = ${Thread.currentThread().name} came from Thread = $tName")
}


suspend fun myFun2(n : Int, tName: String){
    println("myFun2 method called from Thread = $tName, for i = $n")
    println("myFun2 -> executing on Thread = ${Thread.currentThread().name} came from Thread = $tName")
    delay(1000)
    val x = n * n * n;
    println("myFun2 -> performing cube operation on Thread = ${Thread.currentThread().name} for i = $n came from Thread = $tName")
    myFun3(x, Thread.currentThread().name, tName);
    println("myFun2 method finished for i = $n, on Thread = ${Thread.currentThread().name}, came from Thread = $tName")
}

suspend fun myFun3(n : Int, parentFunThread : String, cThread: String){
    if(!fun3Thread.equals(parentFunThread) || !fun3Thread.equals(cThread) || !parentFunThread.equals(cThread)){
        println("--------------------------------------------Found-------------------------")
    }
    println("myFun3 method called from Thread = $parentFunThread, for x = $n through coroutineThread = $cThread")
    println("myFun3 -> executing on Thread = $fun3Thread, came from Thread = $parentFunThread, coroutineThread = $cThread")
    println("myFun3 -> final value of x = $n onThread = $fun3Thread, came from Thread = $parentFunThread, coroutineThread = $cThread")
    println("myFun3 method finished for x = $n, on Thread = $fun3Thread, came from Thread = $parentFunThread, coroutineThread = $cThread")
}

由于我自己创建了这些挂起函数,因此执行非常简单,就像普通函数一样,它们的行为不像(暂停当前协程,将协程与底层线程分离:使线程可用于其他协程)

它们都在它们调用的同一个线程上执行。

当我在挂起函数中调用内置挂起函数(delay(1000))时,底层线程被切换,结果不同。

因为挂起功能有多种方式,例如(retrofit中的api调用方法、房间数据库查询功能和延迟功能,如这里)

我的问题是android的哪个组件执行这些挂起函数?

提前致谢。`

android multithreading kotlin-coroutines
1个回答
0
投票

简单解释:

如果没有挂起,函数会在同一个线程上运行。

否则协程将暂停,线程将被释放以用于其他任务,并且协程可能会在不同的线程上恢复。

延迟、网络调用等任务可以在内置挂起函数中切换线程。

结论

所有这些操作均由 Kotlin 协程库管理。

它们将在哪个线程上运行由

Dispatcher
决定。

协程调度程序

© www.soinside.com 2019 - 2024. All rights reserved.