kotlin 协程无法在命令行中工作

问题描述 投票:0回答:1

我有以下程序:

//Main.kt
import kotlinx.coroutines.*
import java.util.concurrent.*

fun main() {
        val scope = CoroutineScope(Job() + Dispatchers.Default)

        scope.launch{
                println("hello")
        }
}

我尝试在命令行中运行它:

i@LAPTOP:/mnt/d/PROJECTS$ ls
Main.kt  annotations-23.0.0.jar  kotlin-stdlib-1.9.21.jar  kotlinx-coroutines-core-jvm-1.8.0-RC2.jar
i@LAPTOP:/mnt/d/PROJECTS$ kotlinc Main.kt -cp annotations-23.0.0.jar:kotlin-stdlib-1.9.21.jar:kotlinx-coroutines-core-jvm-1.8.0-RC2.jar
i@LAPTOP:/mnt/d/PROJECTS$ java -cp annotations-23.0.0.jar:kotlin-stdlib-1.9.21.jar:kotlinx-coroutines-core-jvm-1.8.0-RC2.jar:. MainKt
i@LAPTOP:/mnt/d/PROJECTS$

我希望在命令行中看到hello,但由于某种原因我的程序没有打印任何内容。 为什么?

kotlin jvm kotlin-coroutines kotlinc
1个回答
1
投票

这是因为您在后台启动了协程并立即完成了应用程序的运行,因此协程甚至没有机会开始执行。

如果您想等待协程完成,请使用

runBlocking
而不是
launch


fun main() {
    runBlocking {
        println("hello")
    }
}

您也可以在启动后简单地执行

Thread.sleep(1000)
,但通常我们不应该假设异步任务将花费特定的时间。

© www.soinside.com 2019 - 2024. All rights reserved.