【发布时间】:2020-10-10 08:08:29
【问题描述】:
我有以下代码,我正在尝试并行运行协程。但是,代码不会并行运行。所有股票价格返回需要 30 秒,而不是 10 秒。但是,如果我使用 GlobalScope.launch,它确实可以正常工作。我从文档中收集到我们应该避免使用 GlobalScope 并使用协程范围。你能帮助理解为什么这不是并行运行吗?
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)
}
【问题讨论】:
-
你在主线程上运行你的协程,
Thread.sleep(10000)阻塞了它。将Thread.sleep更改为delay,它会挂起线程而不是阻塞它。 -
使用
async和Dispatchers.IOasync(Dispatchers.IO) { getStockPrice(company) } -
@IR42 你能详细说明一下吗?