首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >CoRoutine异步没有并行运行。

CoRoutine异步没有并行运行。
EN

Stack Overflow用户
提问于 2020-06-20 02:30:03
回答 1查看 770关注 0票数 1

我有下面的代码,我正在尝试运行协同并行。但是,代码不并行运行。所有的股票价格都需要30秒才能返回,而不是10秒。但是,如果我使用GlobalScope.launch,它确实可以正常工作。我从文档中收集到,我们应该避免使用GlobalScope,并使用协同范围。你能帮助理解为什么这不是并行运行吗?

代码语言:javascript
运行
复制
import kotlinx.coroutines.*

suspend fun getStockPrice(company: String) : Int{
    println("Fetching Stock Price")
    Thread.sleep(10000)
    return 100
}



fun CoroutineScope.launchCoRoutines() {
    val companies = listOf<String>("Google", "Amazon", "Microsoft")

    launch {

        var startTime = System.currentTimeMillis()
        val sharePrice = mutableListOf<Deferred<Int>>()
        for (company in companies) {
            sharePrice += async {
                getStockPrice(company).toInt()
            }
        }

        for (share in sharePrice) {
            println(share.await())
        }
        var endTime = System.currentTimeMillis()

        println(endTime - startTime)

    }


}

 fun main()  {
     runBlocking{
         launchCoRoutines()
     }
     println("Request Sent")
    Thread.sleep(55000)
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-20 02:34:06

答案可以在这里找到:

Kotlin: coroutineScope is slower than GlobalScope

如前所述:

coroutineScope没有定义自己的调度程序,因此您可以从调用方继承它,在本例中是由runBlocking创建的。它使用调用的单个线程。

编辑:您可以使用此函数。

代码语言:javascript
运行
复制
fun launchCoRoutines() {
    val companies = listOf<String>("Google", "Amazon", "Microsoft")

    launch(Dispatchers.Default) { // will get dispatched to DefaultDispatcher 

        var startTime = System.currentTimeMillis()
        val sharePrice = mutableListOf<Deferred<Int>>()
        for (company in companies) {
            sharePrice += async {
                getStockPrice(company).toInt()
            }
        }

        for (share in sharePrice) {
            println(share.await())
        }
        var endTime = System.currentTimeMillis()

        println(endTime - startTime)
    }
}

编辑2:见@动画萨胡岛评论,这是最好的答案

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62480961

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档