这是我的测试代码。
test("capacity = 3, but send 4 before receive") {
val current = System.currentTimeMillis()
val channel = Channel<Int>(capacity = 3)
launch {
repeat(5) {
delay(100)
println("[${getElapsedTime(current)}] send $it")
channel.send(it)
}
channel.close()
}
delay(1000)
launch {
for (msg in channel) {
println("[${getElapsedTime(current)}] receive $msg")
delay(1000)
}
}
}
我原本打算发送 3 件物品,但停止发送了。收到 1 件物品后,我预计会恢复发送。
但是,发送 4 件后就停止发送。为什么会这样?
这是结果:
[110 ms] send 0
[221 ms] send 1
[326 ms] send 2
[432 ms] send 3
[1017 ms] receive 0
[1123 ms] send 4
[2019 ms] receive 1
[3026 ms] receive 2
[4028 ms] receive 3
[5034 ms] receive 4
我预计:
[110 ms] send 0
[221 ms] send 1
[326 ms] send 2
[1017 ms] receive 0
[1123 ms] send 3
[2019 ms] receive 1
[2128 ms] send 4
[3026 ms] receive 2
[4028 ms] receive 3
[5034 ms] receive 4
将 3 个项目放入通道后,发送方仍在继续,“生成”第 4 个项目,尝试发送它,然后由于通道空间不足,它必须等待
send()
。当时第四件还没有真正发送,但制作人已经越过println
线了。