Last active
May 25, 2023 06:20
-
-
Save siddharth1001/2d179c4a21814d53fdd14c02aaa40669 to your computer and use it in GitHub Desktop.
Writing a simple coroutine which performs concurrent execution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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