因此,第一次查看协程时,我想并行处理大量数据并等待它完成。我环顾四周,看到了 RunBlocking 和 Await 等,但不知道如何使用它。
到目前为止我已经
val jobs = mutableListOf<Job>()
jobs += GlobalScope.launch { processPages(urls, collection) }
jobs += GlobalScope.launch { processPages(urls, collection2) }
jobs += GlobalScope.launch { processPages(urls, collection3) }
然后我想知道/等待这些完成
最佳答案
如果您使用结构化并发的概念,则无需手动跟踪并发作业。假设您的 processPages
函数执行某种阻塞 IO,您可以将代码封装到以下挂起函数中,该函数在专为此类工作设计的 IO 调度程序中执行您的代码:
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
:
runBlocking {
processAllPages()
}
关于multithreading - Kotlin 协程 : Waiting for multiple threads to finish,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54854187/