简体   繁体   English

kotlin协程切换规则?

[英]kotlin coroutine switching rule?

I want to make two process daemons like aGroup and bGroup.我想制作两个进程守护进程,例如 aGroup 和 bGroup。 However, bGroup's never started when aGroup doesn't have dealy anyone can tell me why it happened?但是,当 aGroup 没有交易时, dealy从未启动过任何人都可以告诉我为什么会这样吗? and what is the best way to make daemon which running forever with coroutine.以及使守护程序与协程永远运行的最佳方法是什么。

thanks谢谢

@Test
fun `test`() {
    runBlocking {

        val one = async(start = CoroutineStart.LAZY) {
            while (true) {
                runAGroup();
            }
        }.start()

        (1..10).forEach {

            async(start = CoroutineStart.LAZY) {

                while (true) {
                    runBGroup(it)
                }

            }.start()
        }
    }
}


suspend fun runAGroup() {
    println("[AGroup] Main")
    // delay(1000L)  <--- here
}

suspend fun runBGroup(name: Int) {
    println("[BGrouop] $name (1000L)")
    delay(1000L)

} }

runBlocking without an explicit dispatcher uses an event loop to dispatch between coroutines.没有显式分派器的runBlocking使用事件循环在协程之间分派。 Because your runGroupA runs without interruptions there is no chance for other coroutines to run.因为你的runGroupA运行没有中断,所以其他协程没有机会运行。 If you specify a other Dispatcher eg Dispatchers.Default you will see that the other coroutine runs as well.如果您指定了其他调度程序,例如Dispatchers.Default ,您将看到其他协程也运行。

runBlocking(Dispatchers.Default) {
    val one = async(start = CoroutineStart.LAZY) {
        while (true) {
            runAGroup();
        }
    }.start()

    (1..10).forEach {

        async(start = CoroutineStart.LAZY) {

            while (true) {
                runBGroup(it)
            }

        }.start()
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM