Channel 通道
Channel 协程间通信、buffer、produce 构建器、ticker
Channel 通道
Channel 是协程之间的通信管道——类似 BlockingQueue 但非阻塞。
学完本章你将: 掌握 Channel 通信、buffer、produce 构建器。
基本用法
kotlin
fun main() = runBlocking {
val channel = Channel<Int>()
// 生产者
launch {
for (i in 1..5) {
channel.send(i)
println("发送: $i")
}
channel.close()
}
// 消费者
for (value in channel) {
println("接收: $value")
}
}
缓冲区
kotlin
// 无缓冲——send 会挂起直到有人 receive
val rendezvous = Channel<Int>()
// 有缓冲——缓冲满后才挂起
val buffered = Channel<Int>(capacity = 3)
// 无限——永不挂起(Conflated 只保留最新)
val conflated = Channel<Int>(Channel.CONFLATED)
produce 构建器
kotlin
fun CoroutineScope.produceNumbers() = produce {
for (i in 1..5) {
send(i)
}
}
fun main() = runBlocking {
val channel = produceNumbers()
channel.consumeEach { println(it) }
}
Channel vs Flow
| Channel | Flow | |
|---|---|---|
| 冷/热 | 热 | 冷 |
| 用途 | 协程间通信 | 数据流处理 |
| 多订阅者 | 不支持 | 每次 collect 独立 |