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

相关推荐
Goway_Hui19 小时前
【KMP for OpenHarmony】-- 在鸿蒙工程中使用 Apollo-Kotlin
华为·kotlin·harmonyos
释厄62321 小时前
AI 军备竞赛悖论——为 AI 卖游戏但 AI 需要游戏母场景
人工智能·游戏·kotlin
D e re k ZH1 天前
保序回归:从 PAVA 到可并堆的单调约束优化
c++·算法·数据挖掘·回归·kotlin
Goway_Hui1 天前
【KMP for OpenHarmony】Cache4k 0.14.0 鸿蒙适配
华为·kotlin·harmonyos
YB13751 天前
kotlin与函数式编程
kotlin
我是唐青枫2 天前
Kotlin Delegation 委托详解
开发语言·kotlin
唐青枫2 天前
Kotlin Inheritance(继承)详解:语法、原理、实战 Demo
kotlin
alexhilton3 天前
用Konsist与Lint强制执行设计系统契约
android·kotlin·android jetpack
唐青枫3 天前
Kotlin Delegation 委托详解
kotlin
传奇开心果4 天前
Compose Multiplatform 共享边界实战:架构契约、互操作同步与可回退设计
android·kotlin