Skip to content

Instantly share code, notes, and snippets.

@siddharth1001
Created May 25, 2023 08:52
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/e791000ddb39d83d96f534dab0fbece0 to your computer and use it in GitHub Desktop.
Save siddharth1001/e791000ddb39d83d96f534dab0fbece0 to your computer and use it in GitHub Desktop.
How to write coroutines efficiently - 2
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