Jul*_*aad 3 android kotlin kotlin-coroutines
在他关于 Kotlin 中的结构化并发的文章 ( https://medium.com/@elizarov/structured-concurrency-722d765aa952 ) 中,Roman Elizarov 通过给出以下示例来解释并行分解:
coroutineScope {
val deferred1 = async { loadImage(name1) }
val deferred2 = async { loadImage(name2) }
combineImages(deferred1.await(), deferred2.await())
}
Run Code Online (Sandbox Code Playgroud)
显然,这段代码是不言自明的。但是,如果我们改为这样写,我们会得到相同的结果吗
coroutineScope {
val result1 = async { loadImage(name1) }.await()
val result2 = async { loadImage(name2) }.await()
combineImages(result1, result2)
}
Run Code Online (Sandbox Code Playgroud)
意思是,两个异步仍然并行运行还是第二个异步调用永远不会运行,直到 result1 可用?
示例 1:
fun main(args: Array<String>) = runBlocking<Unit> {
val time = measureTimeMillis {
val one = async {
delay(1000)
return@async 1
}
val two = async {
delay(3000)
return@async 2
}
println("The answer is ${one.await() + two.await()}")
}
println("Completed in $time ms")
}
Run Code Online (Sandbox Code Playgroud)
结果 1:
The answer is 3
Completed in 3041 ms
Run Code Online (Sandbox Code Playgroud)
示例 2:
fun main(args: Array<String>) = runBlocking<Unit> {
val time = measureTimeMillis {
val one = async {
delay(1000)
return@async 1
}.await()
val two = async {
delay(3000)
return@async 2
}.await()
println("The answer is ${one + two}")
}
println("Completed in $time ms")
}
Run Code Online (Sandbox Code Playgroud)
结果 2:
The answer is 3
Completed in 4043 ms
Run Code Online (Sandbox Code Playgroud)
查看此链接以获取使用异步并发的官方文档
结论
async-await-async-await 将导致纯顺序代码
async-async-await-await 将并行运行
| 归档时间: |
|
| 查看次数: |
2038 次 |
| 最近记录: |