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

相关推荐
ai2work1 小时前
ch15 加载模型与初始化上下文
kotlin
hai_android2 小时前
Kotlin / Android 常用函数使用示例手册
android·java·kotlin
hai_android3 小时前
Android MeasureSpec 详解
android·java·kotlin
ai2work6 小时前
ch11 持久化:DataStore + Gson 多会话
kotlin
JMchen9 小时前
实战案例:实现120fps流畅的渐变进度条
android·kotlin·canvas
传奇开心果编程1 天前
【Jetpack Compose基础语法学与练】第8课 rememberSaveable,页面旋转/系统重建保留状态
android·学习·ui·kotlin·android jetpack
传奇开心果编程1 天前
【Jetpack Compose基础语法学与练】第7课 if条件渲染 + 列表基础(LazyColumn)
学习·ui·kotlin·android jetpack
ai2work1 天前
ch12 系统能力接入:TTS、剪贴板、分享、文件选择器
kotlin
传奇开心果编程1 天前
【Jetpack Compose基础语法学与练】第9课 SideEffect副作用 + LaunchedEffect,处理异步任务和生命周期
android·学习·ui·kotlin·android jetpack
不要喷香水2 天前
00-总览与架构
kotlin·app·档案管理