kotlin协程接收管道ReceiveChannel生产者produce
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
fun main(args: Array<String>) {
var rc: ReceiveChannel<Int>? = CoroutineScope(Dispatchers.IO).produce {
var i = 0
while (true) {
delay(1000)
send(i)
i++
}
}
runBlocking {
while (true) {
var j = rc?.receive()
println("$j") //每隔1秒收到ReceiveChannel produce发送的值
}
rc?.cancel() //不会关闭,因为无限循环
}
}
本文演示了一个Kotlin协程的例子,通过CoroutineScope和Dispatchers.IO创建了一个协程,使用produce函数创建了一个ReceiveChannel生产者,每秒发送一个递增的整数。runBlocking在一个无限循环中接收并打印这些值,显示了协程的并发执行和非阻塞特性。
https://blog.youkuaiyun.com/zhangphil/article/details/131096899
2034

被折叠的 条评论
为什么被折叠?



