kotlin协程广播管道BroadcastChannel,订阅管道openSubscription
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main(args: Array<String>) {
//广播消息
//也可以把普通Channel转换成广播Channel
//val channel = Channel<Int>()
//val broadcast = channel.broadcast(5)
val broadcastChannel = BroadcastChannel<Int>(5)
CoroutineScope(Dispatchers.IO).launch {
var i = 0
while (true) {
broadcastChannel.send(i)
i++
delay(1000)
}
}
//订阅消息
val receiveChannel1 = broadcastChannel.openSubscription()
val receiveChannel2 = broadcastChannel.openSubscription()
runBlocking {
while (true) {
var v1 = receiveChannel1.receive()
println("rc1 - $v1")
var v2 = receiveChannel2.receive()
println("rc2 - $v2")
}
}
}
kotlin协程接收管道ReceiveChannel生产者produce_kotlin produce_zhangphil的博客-CSDN博客runBlocking 内部启动的3个协程做耗时操作,从输出可以看到3个协程交叉并发执行,runBlocking 会等到3个协程执行结束后才退出,输出结果有明确先后顺序。runBlocking 会等待相同作用域的协程完成才退出runBlocking 本身阻塞线程,但内部运行的协程又非阻塞。kotlin的runBlocking 当内部相同作用域的所有协程都运行结束后,在 runBlocking 之后的代码才能执行, runBlocking 会阻塞所在线程。kotlin协程管道Channel。_kotlin producehttps://blog.csdn.net/zhangphil/article/details/131103072
kotlin协程管道Channel_zhangphil的博客-CSDN博客runBlocking 内部启动的3个协程做耗时操作,从输出可以看到3个协程交叉并发执行,runBlocking 会等到3个协程执行结束后才退出,输出结果有明确先后顺序。runBlocking 会等待相同作用域的协程完成才退出runBlocking 本身阻塞线程,但内部运行的协程又非阻塞。kotlin的runBlocking 当内部相同作用域的所有协程都运行结束后,在 runBlocking 之后的代码才能执行, runBlocking 会阻塞所在线程。kotlin协程管道Channel。https://blog.csdn.net/zhangphil/article/details/131096899
https://blog.csdn.net/zhangphil/category_12224054.htmlhttps://blog.csdn.net/zhangphil/category_12224054.html