Kotlin协程await与join挂起函数异同

Kotlin协程await与join挂起函数异同

Kotlin 复制代码
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking

fun main() {
    runBlocking {
        println("start")

        val job1 = async {
            println("1...")
            val t = (Math.random() * 999).toLong()
            delay(t)
            println("1 $t")
        }

        val job2 = async {
            println("2...")
            val t = (Math.random() * 999).toLong()
            delay(t)
            println("2 $t")
        }

        val job3 = async {
            println("3...")
            val t = (Math.random() * 999).toLong()
            delay(t)
            println("3 $t")
        }

        val r1 = job1.await()
        val r2 = job2.await()
        val r3 = job3.await()

        println("start next")
    }
}

输出:

start

1...

2...

3...

3 103

2 419

1 558

start next

Process finished with exit code 0

Kotlin协程中的await与join挂起函数,在某种程度上说,类似Java的CountDownLatch,等待任务完成后再进行下一步。await与join不同的是,await有返回值,join没有。xxx.await或者xxx.join,只要xxx这条协程运行完成,立即开始下一步。

相关:

https://blog.csdn.net/zhangphil/article/details/90758788

https://blog.csdn.net/zhangphil/article/details/147596030

https://blog.csdn.net/zhangphil/article/details/83443995

https://blog.csdn.net/zhangphil/article/details/154659832

https://blog.csdn.net/zhangphil/article/details/129270875

https://blog.csdn.net/zhangphil/article/details/132621143

https://blog.csdn.net/zhangphil/article/details/135272034

相关推荐
hai_android1 天前
一行 asLiveData,背后是一座生命周期的桥
android·java·kotlin
传奇开心果编程3 天前
【Jetpack Compose娓娓道来】第44课:持久化——让数据“关掉App也不丢”
android·kotlin·移动开发·数据持久化·jetpack compose·ui框架·声明式ui
OriginCoding3 天前
一个 JDK 跑起六个分布式挑战:Kotlin 版 Gossip Glomers(一)
分布式·kotlin
alexhilton4 天前
MVI 让屏幕一次只有一个状态
android·kotlin·android jetpack
金銀銅鐵8 天前
一个 4 个常量的枚举,Kotlin 在字节码里生成了什么
jvm·kotlin
Easyhood9 天前
Android 开发入门实践(十四):Compose 副作用入门与四个常用 API
android·开发语言·kotlin·android jetpack·compose
松仔log10 天前
Kotlin中级——callbackFlow
java·前端·kotlin
zh_xuan10 天前
kotlin常见面试题
开发语言·kotlin·面试题
mmsx10 天前
耳切法切带洞多边形:论文能跑通,真实数据为什么崩
android·kotlin
Kapaseker10 天前
Kotlin 又要加语法糖了:这次轮到 if-else
android·kotlin