How to do it...

  1. Let's start by logging the current thread name to the console:
`print current thread name`()
  1. Start a new coroutine running on a pool of background threads:
`print current thread name`()
var sushiCookingJob: Job
sushiCookingJob = launch(newSingleThreadContext("SushiThread")) {
`print current thread name`()

}
  1. Execute the `cook rice`() function asynchronously in a nested coroutine:
`print current thread name`()
var sushiCookingJob: Job
sushiCookingJob = launch(newSingleThreadContext("SushiThread")) {
`print current thread name`()
val riceCookingJob = launch {
`cook rice`()

}
}
  1. Run the `prepare fish`() and  `cut vegetable`() functions sequentially while the `cook rice`() function is running in the background:
`print current thread name`()
var sushiCookingJob: Job
sushiCookingJob = launch(newSingleThreadContext("SushiThread")) {
`print current thread name`()
val riceCookingJob = launch {
`cook rice`()
}
println("Current thread is not blocked while rice is being
cooked"
)
`prepare fish`()
`cut vegetable`()
}
  1. Wait until the rice-cooking coroutine completes:
`print current thread name`()
var sushiCookingJob: Job
sushiCookingJob = launch(newSingleThreadContext("SushiThread")) {
`print current thread name`()
val riceCookingJob = launch {
`cook rice`()
}
println("Current thread is not blocked while rice is being
cooked"
)
`prepare fish`()
`cut vegetable`()
riceCookingJob.join()
}
  1. Invoke the final `roll the sushi`() function and wait until the main coroutine completes:
`print current thread name`()
var sushiCookingJob: Job
sushiCookingJob = launch(newSingleThreadContext("SushiThread")) {
`print current thread name`()
val riceCookingJob = launch {
`cook rice`()
}
println("Current thread is not blocked while rice is being
cooked"
)
`prepare fish`()
`cut vegetable`()
riceCookingJob.join()
`roll the sushi`()
}
runBlocking {
sushiCookingJob.join()

}
  1. Measure the total time for function execution and log it to the console:
`print current thread name`()
var sushiCookingJob: Job
val time = measureTimeMillis {
sushiCookingJob = launch(newSingleThreadContext("SushiThread")) {
`print current thread name`()
val riceCookingJob = launch {
`cook rice`()
}
println("Current thread is not blocked while rice is being
cooked"
)
`prepare fish`()
`cut vegetable`()
riceCookingJob.join()
`roll the sushi`()
}
runBlocking {
sushiCookingJob.join()
}
}
println("Total time: $time ms")
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.35.158