kotlin 协程多次启动

kok*_*tin 3 coroutine kotlin kotlin-coroutines

如何在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() 
}
Run Code Online (Sandbox Code Playgroud)

Neo*_*Neo 5

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

GlobalScope.launch {

   launch { first() }
   launch { second() }
}
Run Code Online (Sandbox Code Playgroud)

这将永远运行,直到取消和/或抛出内部异常。如果你在协程内部不需要太多资源并且在使用时正确释放它们,你应该永远不会遇到 StackOverFlow 问题。


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

  • @MarkoTopolnik我已经使用 VisualVM 测试了上面的代码和 OP 的代码,并观察到 ​​`DispatchedContinuation`、`first$1`、`second$1` 对象的内存泄漏。如果我使用“delay(0)”或“yield()”而不是“delay(1000L)”,我在启动后不久就会收到 OutOfMemoryError 。在我将“tailrec”关键字添加到函数中后,没有出现内存泄漏。 (2认同)