我有下面的代码,我正在尝试运行协同并行。但是,代码不并行运行。所有的股票价格都需要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)
}
发布于 2020-06-20 02:34:06
答案可以在这里找到:
如前所述:
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:见@动画萨胡岛评论,这是最好的答案
https://stackoverflow.com/questions/62480961
复制相似问题