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

30-通道缓存

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

12.7.4 通道缓存

到目前为止,所介绍的通道都没有涉及任何缓存,当协程的发送方和接收方使用通道传输数据时,如果首先调用send,那么send被挂起,直到receive被调用;如果首先调用receive,那么receive被挂起,直到send被调用。

除此之外,使用通道的工厂函数和生产者构建器还可以定义一个带有缓存的通道,其中,capacity(默认为0)为通道的缓冲区大小。缓冲区允许发送方在协程挂起之前发送多个数据,直到缓冲区被阻塞为止。代码如下。

fun main(args: Array<String>) = runBlocking<Unit> {
    val channel = Channel<Int>(3)   //创建一个带缓存的Channel
    //启动发送协程
    val sender = launch(coroutineContext) {
        repeat(10) {
            println("Sending $it")
            channel.send(it)  //当缓存区满时,send将会挂起
            println("$it add to the buffer")
        }
    }
    delay(1000)
    sender.cancel()
}

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

Sending 0
0 add to the buffer
Sending 1
1 add to the buffer
Sending 2
2 add to the buffer
Sending 3

在上面的实例中,使用Channel函数创建一个大小为3的缓存通道,前3个元素被添加到缓冲区中,当发送第4个元素时,channel.send()将被挂起。