Created
May 25, 2023 08:52
-
-
Save siddharth1001/e791000ddb39d83d96f534dab0fbece0 to your computer and use it in GitHub Desktop.
How to write coroutines efficiently - 2
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
suspend fun performBlockingOperationSuspended(jobName: String) { | |
// non-blocking delay - delay() is a suspending function un-like Thread.sleep() | |
delay(1000) | |
println("Blocking operation completed. jobName = $jobName, thread : ${Thread.currentThread().name}") | |
} | |
fun main() = runBlocking { | |
val executionTime = measureTimeMillis { | |
val job1 = launch { | |
performBlockingOperationSuspended("job1") | |
} | |
val job2 = launch { | |
performBlockingOperationSuspended("job2") | |
} | |
val job3 = launch { | |
performBlockingOperationSuspended("job3") | |
} | |
println("Coroutine launched") | |
joinAll(job1, job2, job3) | |
} | |
println("Total execution time: $executionTime ms") | |
} | |
/* | |
Console Output: | |
Coroutine launched | |
Blocking operation completed. jobName = job1, thread : main | |
Blocking operation completed. jobName = job2, thread : main | |
Blocking operation completed. jobName = job3, thread : main | |
Total execution time: 1016 ms | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment