Kotlin await等待多个异步任务都完成后才进行下一步操作

Kotlin await等待多个异步任务都完成后才进行下一步操作

Kotlin 复制代码
import kotlinx.coroutines.*

fun main() {
    runBlocking {
        val tagA = "a"
        val tagB = "b"

        val a = async {
            worker(tagA)
        }

        val b = async {
            worker(tagB)
        }

        println("${System.currentTimeMillis()} 等待 $tagA $tagB 都完成...")
        val c = "${System.currentTimeMillis()} ${a.await()} ${b.await()}"

        println("${System.currentTimeMillis()} $tagA $tagB 都完成! $c")
    }
}

suspend fun worker(tag: String) {
    println("${System.currentTimeMillis()} $tag start")

    val r = Math.random() * 100
    val t = r.toLong() * 10
    delay(t)

    println("${System.currentTimeMillis()} $tag 完成 time=$t")
}

代码运行后,必须等待a,b两个异步任务都返回结果后才能进行下一步操作。

1745847553470 等待 a b 都完成...

1745847553478 a start

1745847553480 b start

1745847553822 b 完成 time=330

1745847553960 a 完成 time=470

1745847553961 a b 都完成! 1745847553470 kotlin.Unit kotlin.Unit

这在业务开发中比较有用,试想一种场景,一个任务c的执行,必须依赖(等待)另外两个并行子任务a,b的结果,但这两个并行任务a、b何时结束何时返回结果并不确定。把a、b包装成suspend任务,通过关键字await(),等待两个异步任务a,b都完成后才进行下一步c。

Java线程同步与阻塞ReentrantLock - Condition替换wait - notify_reentrantlock 替换 notify-CSDN博客文章浏览阅读666次。import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;public class Main { private ReentrantLock lock = new ReentrantLock(false); private Condition con..._reentrantlock 替换 notifyhttps://blog.csdn.net/zhangphil/article/details/96360104新Java并发线程控制:CountDownLatch等待所有线程运行完毕才执行_countdownlatch倒计时结束了,但是方法没有执行完-CSDN博客文章浏览阅读1.9k次。本文详细介绍Java并发中CountDownLatch的使用方法,演示如何利用它等待一组线程完成后再执行后续操作,适用于需要同步多个线程场景。https://blog.csdn.net/zhangphil/article/details/83443995

相关推荐
消失的旧时光-19434 小时前
kmp需要技能
android·设计模式·kotlin
雨白6 小时前
协程间的通信管道 —— Kotlin Channel 详解
android·kotlin
天一生水water6 小时前
均值回归(配对交易)策略
均值算法·回归·kotlin·量化交易
Dashing7 小时前
KN:Kotlin 与 OC 交互
ios·kotlin
Tang102415 小时前
一次讲清楚 Kotlin 的 suspend 关键字到底做了什么?
kotlin
雨白1 天前
掌握协程的边界与环境:CoroutineScope 与 CoroutineContext
android·kotlin
小仙女喂得猪1 天前
2025 跨平台方案KMP,Flutter,RN之间的一些对比
android·前端·kotlin
Kapaseker2 天前
酷炫的文字效果 — Compose 文本着色
android·kotlin
雨白2 天前
让协程更健壮:全面的异常处理策略
android·kotlin
Jeled2 天前
AI: 生成Android自我学习路线规划与实战
android·学习·面试·kotlin