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

相关推荐
Kapaseker1 小时前
一杯美式搞定 Kotlin 空安全
android·kotlin
FunnySaltyFish19 小时前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
Kapaseker1 天前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
Kapaseker2 天前
实战 Compose 中的 IntrinsicSize
android·kotlin
A0微声z4 天前
Kotlin Multiplatform (KMP) 中使用 Protobuf
kotlin
alexhilton4 天前
使用FunctionGemma进行设备端函数调用
android·kotlin·android jetpack
lhDream5 天前
Kotlin 开发者必看!JetBrains 开源 LLM 框架 Koog 快速上手指南(含示例)
kotlin
RdoZam5 天前
Android-封装基类Activity\Fragment,从0到1记录
android·kotlin
Kapaseker5 天前
研究表明,开发者对Kotlin集合的了解不到 20%
android·kotlin
糖猫猫cc6 天前
Kite:两种方式实现动态表名
java·kotlin·orm·kite