有没有办法获得与下面的代码片段相同的行为但使用协程?
更新的代码片段:
fun main(args: Array<String>) = runBlocking {
val executor = Executors.newFixedThreadPool(50)
log.info("Start")
val jobs = List(300) {
executor.submit {
log.info("worker #$it started")
sleep(1000L)
log.info("worker #$it done")
}
}
jobs.forEach { it.get() }
executor.shutdown()
log.info("All done!")
}
如何以并行因子 == 50 运行 300 个作业,但不创建 50 个真实线程?
更新 2:解决方案
再次阅读Coroutines Guide后,我发现Fan-out 示例正是我想要的。因此,我的示例如下所示:
fun produceTasks() = produce {
for (taskId in 1..300) {
send(
async(start = CoroutineStart.LAZY) {
delay(1000) // simulate long work
taskId
}
)
}
close()
}
fun launchWorker(index: Int, channel: ProducerJob<Deferred<Int>>) = launch {
channel.consumeEach {
val result = it.await()
log.info("Worker #$index done task #$result")
}
}
fun main(args: Array<String>) = runBlocking {
val tasks = produceTasks()
val workers = List(50) { launchWorker(it + 1, tasks) }
workers.forEach { it.join() }
log.info("Done")
}