简体   繁体   English

kotlin coroutine val vs fun

[英]kotlin coroutine val vs fun

I'm new learner to coroutine and Kotlin. 我是coroutine和Kotlin的新学徒。 Why do I obtain different results, case 1 and 2 below? 为什么我会得到不同的结果,下面的情况1和2?

fun main(args: Array<String>) = runBlocking {
    fun a() = async(CommonPool) {
        println("start A")
        delay(1000)
        println("finish A")
    }

    fun b() = async(CommonPool) {
        println("start B")
        delay(1000)
        println("finish B")
    }

    //case 1
    a().await()
    b().await()

    //case 2
    val A = a()
    val B = b()
    A.await()
    B.await()
}

Is this val style coding basic? 这种val样式编码是基本的吗?

The case 1 is equivalent to 案例1相当于

val A = a()
await(A)
val B = b()
await(B)

That is, you start A , await it (here the coroutine suspends), and only then you start B , thus A and B are executed sequentially, not simultaneously. 也就是说,你启动A ,等待它(此处协程暂停),然后才启动B ,因此AB按顺序执行,而不是同时执行。

In case 2 you start both A and B and only then the coroutine suspends waiting for A and B . 情况2中,您同时启动AB ,然后协程暂停等待AB

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM