CoroutineScope Dispatchers.IO异步操作async返回函数,Kotlin
Kotlin
import kotlinx.coroutines.*
fun myFun(a: Int, b: Int, retFun: (sum: Int) -> Unit) {
println("分支myFun开始... ${System.currentTimeMillis()}")
val task = CoroutineScope(Dispatchers.IO).async(start = CoroutineStart.LAZY) {
println("myFun delay... ${System.currentTimeMillis()}")
delay(3000)
println("myFun delay end ${System.currentTimeMillis()}")
a + b
}
CoroutineScope(Dispatchers.IO).launch {
println("myFun launch... ${System.currentTimeMillis()}")
val sum = task.await()
retFun(sum)
println("myFun retFun ${System.currentTimeMillis()}")
}
println("分支myFun结束 ${System.currentTimeMillis()}")
}
fun main(args: Array<String>) {
println("主流程开始 ... ${System.currentTimeMillis()}")
myFun(1, 2) { sum ->
println("主流程等待结果返回...")
println("main : $sum ${System.currentTimeMillis()}")
println("主流程结果返回")
}
println("主流程结束 ${System.currentTimeMillis()}")
Thread.sleep(5000)
}
主流程开始 ... 1703757127994
分支myFun开始... 1703757127995
分支myFun结束 1703757128042
主流程结束 1703757128042
myFun launch... 1703757128045
myFun delay... 1703757128046
myFun delay end 1703757131050
主流程等待结果返回...
main : 3 1703757131052
主流程结果返回
myFun retFun 1703757131052
Process finished with exit code 0