0Pricing
Kotlin Academy · 课时

Channel 类型:会合、缓冲、合并与无限

根据通信模式选择合适的通道类型。

Channel 类型:会合、缓冲、合并与无限 是 CoddyKit 上的免费 Kotlin Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Kotlin Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Kotlin Academy 课程共包含 4 节课。

通道工厂

使用 Channel<T>(capacity) 创建通道。容量决定缓冲和挂起行为。

import kotlinx.coroutines.channels.Channel
val rendezvous = Channel<Int>()              // capacity 0
val buffered   = Channel<Int>(64)            // capacity 64
val unlimited  = Channel<Int>(Channel.UNLIMITED)
val conflated  = Channel<Int>(Channel.CONFLATED)
fun main() { println("Channel types created") }

会合通道(capacity=0)

这是默认通道。send 会一直挂起,直到接收方准备就绪;receive 会一直挂起,直到发送方发送值。双方会合——在同一个位置相遇。

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
    val ch = Channel<Int>() // rendezvous
    launch {
        println("Sending...")
        ch.send(1)  // suspends until receiver is ready
        println("Sent")
    }
    delay(100)
    println("Receiving...")
    println(ch.receive())
}

缓冲通道

缓冲通道允许发送方继续运行,而无需等待,直到缓冲区已满。缓冲区已满时,send 会挂起。

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
    val ch = Channel<Int>(3) // buffer of 3
    launch {
        repeat(3) {
            println("Sending $it")
            ch.send(it) // does not suspend until buffer full
        }
        ch.close()
    }
    delay(500)
    for (v in ch) println("Got $v")
}

Channel.BUFFERED

Channel.BUFFERED 使用默认容量(64)。这等价于 Channel(64)。

import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.*
fun main() = runBlocking {
    val ch = Channel<String>(Channel.BUFFERED)
    println("Default buffer capacity is implementation-defined (~64)")
    ch.close()
}

无限容量通道

Channel.UNLIMITED 永远不会让发送方挂起,而是缓冲所有值。请谨慎使用:内存可能会无限增长。

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
    val ch = Channel<Int>(Channel.UNLIMITED)
    launch {
        repeat(1000) { ch.send(it) } // never suspends
        ch.close()
    }
    var sum = 0
    for (v in ch) sum += v
    println("Sum: $sum")
}

合并通道

Channel.CONFLATED 只保留最近的值。如果新值在前一个值被接收之前到达,旧值就会被丢弃。

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
    val ch = Channel<Int>(Channel.CONFLATED)
    launch {
        repeat(5) { ch.send(it) } // 0..4 sent rapidly
        ch.close()
    }
    delay(50) // let all sends happen
    println("Received: ${ch.tryReceive().getOrNull()}") // likely 4 (last)
}

RENDEZVOUS 与 BUFFERED 的时序

会合通道会同步生产者和消费者。缓冲通道允许生产者超前运行,从而将时序解耦。

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
    val ch = Channel<Int>(Channel.BUFFERED)
    val t = System.currentTimeMillis()
    launch {
        repeat(5) { ch.send(it) } // fast — doesn't wait
        ch.close()
    }
    for (v in ch) { delay(100); println("$v at ${System.currentTimeMillis()-t}ms") }
}

onBufferOverflow 策略

使用 Channel(capacity, onBufferOverflow) 时,可以选择缓冲区已满时的处理方式:SUSPEND(默认)、丢弃最旧值或丢弃最新值。

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
    val ch = Channel<Int>(2, BufferOverflow.DROP_OLDEST)
    launch {
        repeat(5) { ch.trySend(it) } // 0,1,2,3,4 — buffer keeps newest 2
        ch.close()
    }
    for (v in ch) println(v) // likely 3 4
}

选择通道类型

选择指南:需要紧密同步时使用会合通道;需要提高吞吐量时使用缓冲通道;只需要最新值时使用合并通道(例如用户界面状态);对于不允许丢失的事件日志记录,使用无限容量通道。

import kotlinx.coroutines.channels.Channel
// Use cases:
// RENDEZVOUS  — handshake between producer and consumer
// BUFFERED    — decouple I/O-heavy producer from slow consumer
// CONFLATED   — UI updates (only latest matters)
// UNLIMITED   — audit log (never drop)
fun main() { println("Choose based on your loss tolerance and timing needs") }

在 select 中使用通道

select 允许同时等待多个通道,并选择第一个准备就绪的通道。

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.selects.*
fun main() = runBlocking {
    val a = produce { delay(100); send("from a") }
    val b = produce { delay(50);  send("from b") }
    val result = select<String> {
        a.onReceive { it }
        b.onReceive { it }
    }
    println(result) // "from b"
    coroutineContext.cancelChildren()
}

计时器通道

ticker(delay) 会创建一个通道,每隔 delay 毫秒发出一个 Unit,适用于重复轮询。

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
    val ticker = ticker(delayMillis = 100, initialDelayMillis = 0)
    var count = 0
    for (tick in ticker) {
        println("Tick ${++count}")
        if (count == 3) { ticker.cancel(); break }
    }
}

快速检查

哪种通道类型只保留最近的值?

回顾

会合通道:同步运行,无缓冲。缓冲通道:将时序解耦。合并通道:只保留最新值,丢弃旧值。无限容量通道:永远不会让发送方挂起。请根据您对数据丢失的容忍度和吞吐量需求进行选择。

常见问题解答

「Channel 类型:会合、缓冲、合并与无限」课时是免费的吗?

是的 — 「Channel 类型:会合、缓冲、合并与无限」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Kotlin Academy 课程的其余内容,请升级到 CoddyKit PRO。 Kotlin Academy 课程共包含 4 节课。

「Channel 类型:会合、缓冲、合并与无限」这节课中我会学到什么?

根据通信模式选择合适的通道类型。 你通过在浏览器中直接运行的动手代码来练习 Kotlin Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Kotlin Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Kotlin Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「Channel 类型:会合、缓冲、合并与无限」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Kotlin Academy 课中编写并运行代码吗?

能。每节 Kotlin Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Channel 基础:send、receive 与 close
  2. Channel 类型:会合、缓冲、合并与无限
  3. 使用 Mutex 与 Semaphore 管理共享状态
  4. Actor 与结构化状态管理
← 返回 Kotlin Academy