Thoughts of a software developer

11.09.2023 20:05 | Modified 06.12. 10:00
Running coroutines in Kotlin

This is an example on using Kotlin coroutines to run methods parallel and get the results from run methods.

File named HelloWorld.kt

import kotlinx.coroutines.*
import java.time.*

fun main()  {
    val date1 = LocalDateTime.now()
    
    starter()
    
    val date2 = LocalDateTime.now()
    val duration = Duration.between(date1, date2)
    println("running took " + duration.toSeconds() + " s")
}

fun starter() = runBlocking {
    val first = async {
        runner("runner1")
    }
    val second = async {
        runner("runner2")
    }
    val third = async {
        runner("runner3")
    }
    println("Hello")
    println(first.await())
    println(second.await())
    println(third.await())
}

// every runner is set with a 2 second wait
suspend fun runner(name: String): String {
    delay(2000L)
    return name
}

Compile

kotlinc HelloWorld.kt -jvm-target 20 -classpath kotlinx-coroutines-core-jvm-1.6.4.jar -include-runtime -d HelloWorld.jar

Run

kotlin -classpath kotlinx-coroutines-core-jvm-1.6.4.jar:HelloWorld.jar HelloWorldKt

Prints out:

Hello
runner1
runner2
runner3
running took 2 s