kotlin Coroutine 多次启动

kotlin Coroutine multiple launch

如何在 kotlin 中像多线程一样进行多次启动

我想让 first second 永远同时工作!!

喜欢这个代码...

runBlocking {

    // first
    launch{
      first()
    }

    // second
    launch{
       second()
    }
}


suspend fun first(){
    // do something 
    delay(1000L)

    // Recursive call
    first() 
}

suspend fun second(){
    // do something 
    delay(1000L)

    // Recursive call
    second() 
}

如果您的示例代码是您应用程序中唯一的 运行ning 代码,那么它已经可以工作了。如果您需要 运行 与您的应用程序并行使用这两种方法,请将它们包装在 GlobalScope.launch:

GlobalScope.launch {

   launch { first() }
   launch { second() }
}

这将 运行 永远,直到取消 and/or 抛出内部异常。如果您不需要在协程中使用太多资源并在使用时正确释放它们,那么 Whosebug 永远不会有问题。


除了递归代码:尝试按照评论中的建议进行循环。

可以用循环实现无限执行

runBlocking {
    launch { while(true) first() }
    launch { while(true) second() }
}

suspend fun first(){
    // do something 
    delay(1000L)
}

suspend fun second(){
    // do something 
    delay(1000L)
}