Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siddharth1001/2d179c4a21814d53fdd14c02aaa40669 to your computer and use it in GitHub Desktop.
Save siddharth1001/2d179c4a21814d53fdd14c02aaa40669 to your computer and use it in GitHub Desktop.
Writing a simple coroutine which performs concurrent execution
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
fun main() {
runBlocking {
val executionTime = measureTimeMillis {
val job1 = launch { // Coroutine 1
delay(1000)
println("Coroutine 1 completed")
}
val job2 = launch { // Coroutine 2
delay(1000)
println("Coroutine 2 completed")
}
val job3 = async { // Coroutine 3
delay(1000)
"Coroutine 3 result"
}
println("Performing other tasks while coroutines are executing...")
// Wait for all coroutines to complete
joinAll(job1, job2, job3)
val result = job3.await()
println("Coroutine 3 result: $result")
}
println("Total execution time: $executionTime ms")
}
}
/*
Console output:
Performing other tasks while coroutines are executing...
Coroutine 1 completed
Coroutine 2 completed
Coroutine 3 result: Coroutine 3 result
Total execution time: 1023 ms // this value(i.e. 1023) may change a little but should be slightly greater than 1000ms.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment