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

相关推荐
starrycode88812 小时前
【每日一个知识点】Kotlin基础语法核心学习笔记
笔记·学习·kotlin
alexhilton1 天前
学会在Jetpack Compose中加载Lottie动画资源
android·kotlin·android jetpack
用户69371750013841 天前
29.Kotlin 类型系统:智能转换:类型检查 (is) 与类型转换 (as)
android·后端·kotlin
用户69371750013841 天前
30. Kotlin 扩展:为“老类”添“新衣”:扩展函数与扩展属性
android·后端·kotlin
ForteScarlet1 天前
如何解决 Kotlin/Native 在 Windows 下 main 函数的 args 乱码?
开发语言·windows·kotlin
starrycode8881 天前
【每日一个知识点】Kotlin开发基础知识
ui·kotlin
愤怒的代码1 天前
深入理解 IdleHandler:从启动优化到内存管理
android·架构·kotlin
Kapaseker2 天前
一万四千字重温 Android 四大组件
android·kotlin
我爱烤冷面2 天前
kotlin项目实现Java doc的方案:使用Dokka
java·开发语言·kotlin·dokka
jian110582 天前
android java转kotlin,kotlin转java
android·java·kotlin