站长统计
Kotlin协程(三)async和await
Kotlin 协程 (⼀)
Kotlin 协程(⼆) -协程取消与超时
如果顺序执⾏,调起两个挂起函数,执⾏这两个挂起函数的总是时间等于分别执⾏这个两个函数的总和,如⽰例(1)
⽰例(1):
fun main() = runBlocking<Unit> {
val time = measureTimeMillis {
val one = doSomethingUsefulOne()
val two = doSomethingUsefulTwo()
println("The result is ${one + two}")
}
println("Completed in $time ms")
}
suspend fun doSomethingUsefulOne(): Int {
delay(1000L)
return 10
}
suspend fun doSomethingUsefulTwo(): Int {
delay(1000L)
return 33
}
⽰例(1)执⾏结果:
The result is 43
Completed in 2046 ms
async函数类似于 launch函数.它启动了⼀个单独的协程,这是⼀个轻量级的线程并与其它所有的协程⼀起并发的⼯作.不同之处在于 launch 返回⼀个 Job 并且不附带任何结果值,⽽ async 返回⼀个 Deferred —— ⼀个轻量级的⾮阻塞 future,这代表了⼀个将会在稍后提供结果的promise.你可以使⽤ .await() 在⼀个延期的值上得到它的最终结果, 但是 Deferred 也是⼀个 Job,所以如果需要的话,你可以取消它.如⽰例(2)
⽰例(2):
fun main() = runBlocking<Unit> {
val time = measureTimeMillis {
val one = async { doSomethingUsefulOne() }
val two = async { doSomethingUsefulTwo() }
val result1 = one.await()
val result2 = two.await()
println("The result is ${result1 + result2}")
}
println("Completed in $time ms")
}
suspend fun doSomethingUsefulOne(): Int {
delay(1000L)
return 10
}
suspend fun doSomethingUsefulTwo(): Int {
delay(1000L)
return 33
}
⽰例(2)的执⾏结果:
The result is 43
Completed in 1032 ms
通过⽰例(1)和⽰例(2)的执⾏结果,我们可以看出,⽰例(2)的两个挂起函数是并发执⾏的,即:async函数是新起⼀个协程,并发执⾏的
async 可以通过将 start 参数设置为 CoroutineStart.LAZY ⽽变为惰性的.在这种情况下,只有结果通过 await 获取的时候协程才会启动,或者在Job 的 start 函数调⽤的时候,如⽰例(3)
⽰例(3):
fun main() = runBlocking<Unit> {
val time = measureTimeMillis {
val one = async(start = CoroutineStart.LAZY) { doSomethingUsefulOne() }
val two = async(start = CoroutineStart.LAZY) { doSomethingUsefulTwo() }
one.start()
two.start()
val result1 = one.await()
val result2 = two.await()
println("The result is ${result1 + result2}")
}
println("Completed in $time ms")
}
suspend fun doSomethingUsefulOne(): Int {
delay(1000L)
return 9
}
suspend fun doSomethingUsefulTwo(): Int {await和async使用方法
delay(1000L)
return 33
}
⽰例(3)的执⾏结果:
The result is 42
Completed in 1026 ms
在⽰例(3)中,如果没有执⾏start,默认执⾏await⽅法,则one 和 two是顺序执⾏的,one执⾏完之后才执⾏two,如⽰例(4)⽰例(4):
fun main() = runBlocking<Unit> {
val time = measureTimeMillis {
val one = async(start = CoroutineStart.LAZY) { doSomethingUsefulOne() }
val two = async(start = CoroutineStart.LAZY) { doSomethingUsefulTwo() }
val result1 = one.await()
val result2 = two.await()
println("The result is ${result1 + result2}")
}
println("Completed in $time ms")
}
suspend fun doSomethingUsefulOne(): Int { delay(1000L)
return 9
}
suspend fun doSomethingUsefulTwo(): Int { delay(1000L)
return 33
}
⽰例(4)的执⾏结果:
The result is 42
Completed in 2026 ms
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论