我有以下代码正在尝试并行运行协程。但是,代码不会并行运行。所有股票的价格需要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)
}
答案 0 :(得分:1)
可以在这里找到答案:
如上所述:
coroutineScope没有定义自己的调度程序,因此您可以继承它 来自调用者,在这种情况下是由runBlocking创建的。它用 调用它的单线程。
编辑: 您可以使用此功能
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: 看到@Animesh Sahu评论,这是最好的答案