简体   繁体   中英

kotlin coroutine switching rule?

I want to make two process daemons like aGroup and bGroup. However, bGroup's never started when aGroup doesn't have dealy anyone can tell me why it happened? 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. Because your runGroupA runs without interruptions there is no chance for other coroutines to run. If you specify a other Dispatcher eg Dispatchers.Default you will see that the other coroutine runs as well.

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()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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