Kotlin协程:等待多个线程完成

编程入门 行业动态 更新时间:2024-10-26 09:26:31
本文介绍了Kotlin协程:等待多个线程完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

因此,第一次查看协程,我想并行处理数据加载并等待其完成.我环顾四周,看到RunBlocking和Await等,但不确定如何使用它.

So looking at Coroutines for the first time, I want to process a load of data in parallel and wait for it to finish. I been looking around and seen RunBlocking and Await etc but not sure how to use it.

我到目前为止有

val jobs = mutableListOf<Job>() jobs += GlobalScope.launch { processPages(urls, collection) } jobs += GlobalScope.launch { processPages(urls, collection2) } jobs += GlobalScope.launch { processPages(urls, collection3) }

然后我想知道/等待这些完成

I then want to know/wait for these to finish

推荐答案

如果您使用结构化并发概念,则无需手动跟踪当前的工作.假设您的processPages函数执行某种阻塞的IO,则可以将代码封装到以下挂起函数中,该函数在为此工作而设计的IO调度程序中执行代码:

You don't need to manually keep track of your cuncurrent jobs if you use the concept of structured concurrency. Assuming that your processPages function performs some kind of blocking IO, you can encapsulate your code into the following suspending function, which executes your code in an IO dispatcher designed for this kind of work:

suspend fun processAllPages() = withContext(Dispatchers.IO) { // withContext waits for all children coroutines launch { processPages(urls, collection) } launch { processPages(urls, collection2) } launch { processPages(urls, collection3) } }

现在,如果应用程序的最高功能还不是挂起功能,则可以使用runBlocking调用processAllPages:

Now, from if a topmost function of your application is not already a suspending function, then you can use runBlocking to call processAllPages:

runBlocking { processAllPages() }

更多推荐

Kotlin协程:等待多个线程完成

本文发布于:2023-11-23 11:12:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621244.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   线程   Kotlin   协程

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!