- Let's start by logging the current thread name to the console:
`print current thread name`()
- 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`()
}
- 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`()
}
}
- 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`()
}
- 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()
}
- 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()
}
- 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")