协程通道 - 通道容量为 3,但在接收之前发送 4 个项目

问题描述 投票:0回答:1

这是我的测试代码。

    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
kotlin channel coroutine kotlin-coroutine-channel
1个回答
0
投票

将 3 个项目放入通道后,发送方仍在继续,“生成”第 4 个项目,尝试发送它,然后由于通道空间不足,它必须等待

send()
。当时第四件还没有真正发送,但制作人已经越过
println
线了。

© www.soinside.com 2019 - 2024. All rights reserved.