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

相关推荐
进击的cc6 小时前
Android Kotlin:扩展函数如何优雅封装Android API
android·kotlin
进击的cc6 小时前
Android Kotlin:空安全机制在Android中的实战应用
android·kotlin
海盐芝士不加糖10 小时前
我又又又辞职了,然后做了一款“离线版微信”
kotlin·app·android jetpack
Kapaseker11 小时前
你知道屏幕上存在多少个 Window 吗
android·kotlin
stevenzqzq1 天前
Kotlin 进阶指南:中缀函数 (Infix Function)
android·kotlin·compose
Kapaseker1 天前
Android Studio 是如何预览 Compose 的
android·kotlin
__Yvan2 天前
Kotlin 的 ?.let{} ?: run{} 真的等价于 if-else 吗?
android·开发语言·前端·kotlin
tangweiguo030519872 天前
Android WorkManager 完整实战教程(含完整文件)
android·kotlin
顾道长生'2 天前
(Arxiv-2026)HiAR:基于分层去噪的高效自回归长视频生成
回归·kotlin·音视频·长视频生成
Kapaseker2 天前
Compose 中 CompositionLocalProvider 到底是干啥的
android·kotlin