使用 kotlin 频道无法收到少量消息

Couldn't receive few messages using kotlin channel

我有以下 kotlin 协程代码。

    import kotlinx.coroutines.*
    import kotlinx.coroutines.channels.*

    fun main() = runBlocking {

        val channel =  Channel<Int>()
        val job = launch {
            for(x in 1..5) {
                println("sending $x")
                channel.send(x)
            }

            channel.close()
        }

        for (y in channel) {
            // if (!channel.isClosedForReceive && !channel.isClosedForSend)
            println( "received ${channel.receive()} isClosedForSend ${channel.isClosedForSend} isClosedForReceive ${channel.isClosedForReceive}  " )
        }
        job.join()
    }

以上程序的输出是(接收端少了几个元素)-

sending 1
sending 2
received 2 isClosedForSend false isClosedForReceive false  
sending 3
sending 4
received 4 isClosedForSend false isClosedForReceive false  
sending 5

如果我取消对 if (!channel.isClosedForReceive && !channel.isClosedForSend) 行的注释,我会得到相同的输出,但有异常。

    sending 1
    sending 2
    received 2 isClosedForSend false isClosedForReceive false  
    sending 3
    sending 4
    received 4 isClosedForSend false isClosedForReceive false  
    sending 5
    Exception in thread "main" kotlinx.coroutines.channels.ClosedReceiveChannelException: Channel was closed
        at kotlinx.coroutines.channels.Closed.getReceiveException(AbstractChannel.kt:1081)
        at kotlinx.coroutines.channels.AbstractChannel.receiveResult(AbstractChannel.kt:577)
        at kotlinx.coroutines.channels.AbstractChannel.receive(AbstractChannel.kt:570)

如何才能无一例外地获得正确的输出?

你可以写

for (y in channel) {
    println(y)
}