Kotlin 异步不';似乎没有同时运行

Kotlin 异步不';似乎没有同时运行,kotlin,Kotlin,以下代码使用2个异步函数调用: import kotlinx.coroutines.* import kotlin.system.* fun main() = runBlocking<Unit> { val time = measureTimeMillis { val one = async { doSomethingUsefulOne() } val two = async { doSomethingUsefulTwo() }

以下代码使用2个异步函数调用:

import kotlinx.coroutines.*
import kotlin.system.*

fun main() = runBlocking<Unit> {
    val time = measureTimeMillis {
        val one = async { doSomethingUsefulOne() }
        val two = async { doSomethingUsefulTwo() }
        println("The answer is ${one.await() + two.await()}")
    }
    println("Completed in $time ms")    
}

suspend fun doSomethingUsefulOne(): Int {

    delay(3000L) // pretend we are doing something useful here
    println("first")
    return 13
}

suspend fun doSomethingUsefulTwo(): Int {

    delay(1000L) // pretend we are doing something useful here, too
    println("second")
    return 29
}
导入kotlinx.coroutines*
导入kotlin.system*
fun main()=运行阻塞{
val时间=测量值{
val one=async{dosomethinguselfone()}
val two=async{dosomethinguselftwo()}
println(“答案是${one.await()+two.await()}”)
}
println(“在$time毫秒内完成”)
}
suspend fun dosomethinguselfone():Int{
延迟(3000L)//假装我们正在做一些有用的事情
println(“第一”)
返回13
}
suspend fun dosomethingusselftwo():Int{
delay(1000L)//假装我们也在做一些有用的事情
println(“第二”)
返回29
}

println的结果是先打印“first”,然后打印“second”。但是根据文档,这些异步应该同时运行。但既然第一个有3秒的延迟,为什么它的println会先运行呢?事实上,我把println放在延迟之前还是之后都没关系。我得到了相同的结果。

这两个函数之间存在差距的原因是您在打印行中调用它们的方式:

println("The answer is ${one.await() + two.await()}")
尝试将.await()更改为.launch()。
wait()调用函数,然后停止,直到完成为止。

在我的系统上,它的行为与预期的一样<代码>第二个在第一个之前打印。最后打印的
答案是42
在3022毫秒内完成。你真的确定你的观察结果属于显示的代码吗?你可以在线尝试代码