kotlin协程接收管道ReceiveChannel生产者produce

kotlin协程接收管道ReceiveChannel生产者produce

 

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce

fun main(args: Array) {
    var rc: ReceiveChannel? = 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协程管道Channel_zhangphil的博客-CSDN博客runBlocking 内部启动的3个协程做耗时操作,从输出可以看到3个协程交叉并发执行,runBlocking 会等到3个协程执行结束后才退出,输出结果有明确先后顺序。runBlocking 会等待相同作用域的协程完成才退出runBlocking 本身阻塞线程,但内部运行的协程又非阻塞。kotlin的runBlocking 当内部相同作用域的所有协程都运行结束后,在 runBlocking 之后的代码才能执行, runBlocking 会阻塞所在线程。kotlin协程管道Channel。https://blog.csdn.net/zhangphil/article/details/131096899

 

你可能感兴趣的:(kotlin,协程,kotlin,协程)