【问题标题】:Async doesn't appear to run concurrently异步似乎没有同时运行
【发布时间】:2019-12-05 08:02:35
【问题描述】:

以下代码使用了 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
}

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

【问题讨论】:

  • 在我的系统上,它的行为与预期的一样。 second 在 first 之前打印。最后打印出The answer is 42 和Completed in 3022 ms。您确定您的观察结果属于显示的代码吗?
  • 你可以在网上试一下代码here

标签: kotlin


【解决方案1】:

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

println("The answer is ${one.await() + two.await()}")

尝试将 .await() 更改为 .launch()。 Await() 调用该函数,然后停止,直到它完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多