I have the following program:
//Main.kt
import kotlinx.coroutines.*
import java.util.concurrent.*
fun main() {
val scope = CoroutineScope(Job() + Dispatchers.Default)
scope.launch{
println("hello")
}
}
I tried to run it in a command line:
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$
I expected to see hello in the command line but for some reason my program prints nothing. Why?
This is because you launched the coroutine in the background and immediately finished running your application, so the coroutine didn't even have a chance to start executing.
If you want to wait for the coroutine to finish, use
runBlockinginstead oflaunch:You can also simply do
Thread.sleep(1000)after launching, but generally we shouldn't assume an asynchronous task will take a specific amount of time.