Kotlin提供了coroutine的并发功能,方便处理并行任务。
import kotlinx.coroutines.*
suspend fun suspendFunction1(): String {
delay(1000)
return "Function 1"
}
suspend fun suspendFunction2(): String {
delay(500)
return "Function 2"
}
fun main() = runBlocking {
val result = coroutineScope {
val deferred1 = async { suspendFunction1() }
val deferred2 = async { suspendFunction2() }
deferred1.await()
}
println(result)
}
在上面的代码中,我们定义了两个挂起函数suspendFunction1
和suspendFunction2
,它们会分别等待1秒和0.5秒后返回结果。
接着,使用coroutineScope
创建了一个作用域,把两个并发任务封装成async
,并将它们分别赋值给deferred1
和deferred2
。
最后使用deferred1.await()
阻塞当前协程,直到suspendFunction1
返回结果,并将结果赋值给result
。
这样就实现了“并行运行两个挂起函数,并在第一个返回时返回”的功能。
上一篇:并行运行lambda或更好的方法