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

时间:2019-02-24 16:48:45

标签: kotlin coroutine kotlin-coroutines

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

我到目前为止有

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

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

3 个答案:

答案 0 :(得分:3)

如果使用结构化并发的概念,则无需手动跟踪并发作业。假设您的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()
}

答案 1 :(得分:1)

您可以使用async构建器函数来并行处理数据负载:

class Presenter {
    private var job: Job = Job()
    private var scope = CoroutineScope(Dispatchers.Main + job) // creating the scope to run the coroutine. It consists of Dispatchers.Main (coroutine will run in the Main context) and job to handle the cancellation of the coroutine.

    fun runInParallel() {
        scope.launch { // launch a coroutine
            // runs in parallel
            val deferredList = listOf(
                    scope.asyncIO { processPages(urls, collection) },
                    scope.asyncIO { processPages(urls, collection2) },
                    scope.asyncIO { processPages(urls, collection3) }
            )

            deferredList.awaitAll() // wait for all data to be processed without blocking the UI thread

            // do some stuff after data has been processed, for example update UI
        }
    }

    private fun processPages(...) {...}

    fun cancel() {
        job.cancel() // invoke it to cancel the job when you don't need it to execute. For example when UI changed and you don't need to process data
    }
}

扩展功能asyncIO

fun <T> CoroutineScope.asyncIO(ioFun: () -> T) = async(Dispatchers.IO) { ioFun() } // CoroutineDispatcher - runs and schedules coroutines

GlobalScope.launch is not recommended to use,除非您希望协程在整个应用程序生命周期内运行并且不被过早取消。

编辑:如Roman Elizarov所述,您可以尝试不要使用awaitAll()函数,除非您想在处理完所有数据后立即更新UI或立即执行其他操作。

答案 2 :(得分:0)

可以使用以下方法。

fun myTask() {
    GlobalScope.launch {
        val task = listOf(
            async {

            },
            async {

            }
        )
        task.awaitAll()

    }
}