【问题标题】:kotlin coroutine switching rule?kotlin协程切换规则?
【发布时间】:2019-11-19 02:31:47
【问题描述】:

我想创建两个进程守护进程,例如 aGroup 和 bGroup。 但是,当 aGroup 没有 dealy 时,bGroup 永远不会启动 谁能告诉我为什么会这样?以及使守护进程与协程永远运行的最佳方法是什么。

谢谢

@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)

}

【问题讨论】:

    标签: multithreading kotlin kotlin-coroutines


    【解决方案1】:

    runBlocking 没有明确的分派器使用事件循环在协程之间分派。因为你的runGroupA 运行没有中断,所以其他协程没有机会运行。 如果您指定其他调度程序,例如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()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-19
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多