当前位置:嗨网首页>书籍在线阅读

29-多接收者协程

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

12.7.3 多接收者协程

在Kotlin的协程中,多个协程之间可以从同一个通道中发送并接收数据。例如,下面是一个定期产生整数的生产者协程。

fun produces() = produce<Int> {
    var x = 1
    while (true) {
        send(x++)
        delay(100)   //每隔0.1s产生一个整数
    }
}

开启协程来对接收到的数据进行处理。例如,下面的函数主要用来打印协程的编号和接收到的数字。

fun launchProcessor(id: Int, channel: ReceiveChannel<Int>) = launch {
    channel.consumeEach {
        println("Processor:$id  received:$it")  //打印协程的编号和接收到的数字
    }
}

然后,在主线程中开启5个协程来处理接收到的数据。

fun main(args: Array<String>) = runBlocking<Unit> {
    val producer = produces()
    repeat(5) { launchProcessor(it, producer) }
    delay(950)
    producer.cancel()   //取消生产者协程并释放资源
}

运行上面的代码,输出的结果如下。

Processor:0  received:1
Processor:1  received:2
Processor:2  received:3
Processor:4  received:4
Processor:3  received:5
Processor:0  received:6
Processor:1  received:7
Processor:2  received:8
Processor:4  received:9
Processor:3  received:10

当生产者协程被取消时,协程的通道也会被关闭,并最终导致所有正在执行的协程通道的关闭。