为什么在协程中使用 async 和 await 所花费的时间不同?

Why is the time taken different using async and await in a coroutine?

我在学习协程时有一个问题。

fun main() {
    runBlocking {
        val time = measureTimeMillis {
            val a = async {
                delay(1000)
                "1"
            }
            val b = async {
                delay(1000)
                "2"
            }

            val a1 = a.await()
            val b1 = b.await()
        }

        println(time)
    }
}

运行 这需要 1000

fun main() {
    runBlocking {
        val time = measureTimeMillis {
            val a = async {
                delay(1000)
                "1"
            }.await()
            val b = async {
                delay(1000)
                "2"
            }.await()
        }

        println(time)
    }
}

但是运行这需要 2000

我想知道为什么会这样 行为是否根据返回 Deferred 与执行后返回值而改变?

来自 async 文档

By default, the coroutine is immediately scheduled for execution.

在第一种情况下,您只需使用 async 启动两个协程,它们会立即开始执行,当您对它们调用 await 时,它们都已启动并且 运行。所以他们都只需要 1000 毫秒就可以完成。

但在第二种情况下,您启动 a 然后等待它完成,这需要 1000 毫秒,然后您启动 b 并等待它完成,这也需要 1000 毫秒。所以最终这会花费你 2000 毫秒。