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

相关推荐
bytebitx13 小时前
MacOS 编译腾讯 Mars XLog 及使用(已16KB对齐)
kotlin·mac·apk
alexhilton1 天前
让架构边界变成可执行的测试
android·kotlin·android jetpack
数据治理自习室2 天前
AI 应用评测体系(GraphRAG)
android·大数据·人工智能·kotlin
名剑走天下3 天前
Android 面试题大全
android·kotlin
chjif3 天前
Android 设备管控开发实战:自定义 Launcher 如何只显示指定 App?
android·kotlin
非凡ghost3 天前
用 Kotlin 和 Jetpack Compose 重写的安卓视频播放器,原生体验有多流畅?
android·java·kotlin·音视频·软件需求
名剑走天下3 天前
android 面试题
kotlin
蜡台4 天前
Jetpack Compose 稳定性、重组优化(Stable / @NonRestartableComposable)
android·kotlin·compose·jepack
JMchen1234 天前
Jetpack 内核实战(十):实战(下)——编辑页、全局设置与内存泄漏排查
kotlin·内存泄漏·android 实战·datastore 设置·jetpack 项目优化·编辑页开发
雨白4 天前
Kotlin 泛型基础:“万能魔法盒”的诞生
kotlin