Channel 基础:send、receive 与 close
创建通道、发送和接收值,并正确关闭通道。
Channel 基础:send、receive 与 close 是 CoddyKit 上的免费 Kotlin Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Kotlin Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Kotlin Academy 课程共包含 4 节课。
什么是通道
Channel 是一种用于协程之间通信的协程原语——类似于阻塞队列,但会挂起而不是阻塞。您可以把它理解为一条管道:一端发送,另一端接收。
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
val channel = Channel<Int>()
launch {
for (i in 1..5) channel.send(i)
channel.close()
}
for (x in channel) println(x) // 1 2 3 4 5
}send 和 receive
send(value) 会一直挂起,直到接收方准备就绪。receive() 会一直挂起,直到有值可用。
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
val ch = Channel<String>()
launch {
ch.send("ping")
println("sent")
}
val msg = ch.receive()
println("received: $msg")
}关闭通道
channel.close() 会发出不再发送更多值的信号。接收方会获取剩余的缓冲值,然后 for 循环结束。
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
val ch = Channel<Int>(3)
launch {
repeat(3) { ch.send(it) }
ch.close() // signal done
}
for (v in ch) println(v) // 0 1 2, then loop ends
println("Channel consumed")
}isClosedForSend / isClosedForReceive
使用 isClosedForSend(不允许继续发送)和 isClosedForReceive(所有值都已消费)检查通道状态。
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
val ch = Channel<Int>()
launch {
ch.send(1)
ch.close()
}
println(ch.receive())
println("isClosedForReceive: ${ch.isClosedForReceive}")
}produce 构建器
produce { } 是一种协程构建器,它会创建生产者协程并返回一个 ReceiveChannel。代码块结束时,通道会自动关闭。
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun CoroutineScope.squares(n: Int) = produce<Int> {
for (i in 1..n) send(i * i)
}
fun main() = runBlocking {
val sq = squares(5)
for (v in sq) println(v) // 1 4 9 16 25
}consumeEach 扩展
consumeEach { } 会遍历通道,并在代码块抛出异常时取消通道,从而避免资源泄漏。
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
val ch = produce<String> {
send("a"); send("b"); send("c")
}
ch.consumeEach { println(it) }
}tryReceive 和 trySend
非挂起替代方案:trySend / tryReceive 会立即返回 ChannelResult,不会发生挂起。
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
val ch = Channel<Int>(1)
val sendResult = ch.trySend(42)
println("Sent: ${sendResult.isSuccess}")
val recvResult = ch.tryReceive()
println("Got: ${recvResult.getOrNull()}")
}扇出:多个消费者
多个协程可以从同一个通道接收值,从而分配工作,这就是扇出模式。
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
val tasks = produce { repeat(6) { send(it) } }
repeat(3) { worker ->
launch {
for (task in tasks) {
println("Worker $worker: task $task")
}
}
}
}扇入:多个生产者
多个协程可以向同一个通道发送值,合并它们的输出,这就是扇入模式。
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
val results = Channel<String>()
repeat(3) { i ->
launch { results.send("result-$i") }
}
launch {
repeat(3) { println(results.receive()) }
results.close()
}
}流水线模式
将通道连接成一条流水线,其中每个阶段从一个通道读取数据,再写入另一个通道——非常适合数据处理工作流。
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun CoroutineScope.numbers() = produce { for (i in 1..5) send(i) }
fun CoroutineScope.doubled(input: ReceiveChannel<Int>) = produce { for (v in input) send(v * 2) }
fun main() = runBlocking {
val nums = numbers()
val doubled = doubled(nums)
for (v in doubled) println(v) // 2 4 6 8 10
coroutineContext.cancelChildren()
}通道与数据流
通道是热的并且具有状态——它们独立于消费过程而存在。数据流是冷的并且具有声明性——每次收集时都会重新启动。对于数据流,优先使用 Flow;对于生产者与消费者之间的通信,请使用通道。
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.flow.*
// Flow (cold): each collect() re-runs the block
// Channel (hot): shared; multiple receivers share the same stream
fun main() = runBlocking { println("Flow = cold; Channel = hot") }快速检查
调用 channel.close() 时会发生什么?
回顾
send 和 receive 会一直挂起,直到另一端准备就绪。close() 会发出完成信号。使用 produce 创建自动关闭的生产者,使用 consumeEach 安全地遍历通道,并利用通道实现扇入/扇出模式。
常见问题解答
「Channel 基础:send、receive 与 close」课时是免费的吗?
是的 — 「Channel 基础:send、receive 与 close」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Kotlin Academy 课程的其余内容,请升级到 CoddyKit PRO。 Kotlin Academy 课程共包含 4 节课。
「Channel 基础:send、receive 与 close」这节课中我会学到什么?
创建通道、发送和接收值,并正确关闭通道。 你通过在浏览器中直接运行的动手代码来练习 Kotlin Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Kotlin Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Kotlin Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「Channel 基础:send、receive 与 close」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Kotlin Academy 课中编写并运行代码吗?
能。每节 Kotlin Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Channel 基础:send、receive 与 close
- Channel 类型:会合、缓冲、合并与无限
- 使用 Mutex 与 Semaphore 管理共享状态
- Actor 与结构化状态管理