What is the output of this Kotlin code that uses a coroutine and a thread?
import kotlinx.coroutines.* fun main() = runBlocking { launch { println("Start coroutine") delay(100) println("End coroutine") } Thread { println("Start thread") Thread.sleep(50) println("End thread") }.start() delay(200) }
Remember coroutines are lightweight and can suspend without blocking threads.
The coroutine starts and prints immediately, then suspends for 100ms. The thread starts and prints immediately, then sleeps for 50ms. So the thread finishes before the coroutine resumes.
Which statement best describes the difference in resource usage between Kotlin coroutines and threads?
Think about how coroutines suspend without blocking threads.
Coroutines are lightweight because they do not require a dedicated thread and can suspend execution without blocking the underlying thread, saving memory and resources.
What error will this Kotlin code produce?
import kotlinx.coroutines.* fun main() { GlobalScope.launch { println("Coroutine running") delay(100) println("Coroutine finished") } Thread.sleep(50) println("Main finished") }
Consider the lifecycle of GlobalScope coroutines and main thread.
The main thread sleeps 50ms and then prints "Main finished" and exits. The coroutine is launched but may not complete before the program ends, so "Coroutine finished" may never print.
What is the output of this Kotlin program?
import kotlinx.coroutines.* fun main() = runBlocking { launch { println("Coroutine 1 start") delay(100) println("Coroutine 1 end") } launch { println("Coroutine 2 start") delay(50) println("Coroutine 2 end") } Thread { println("Thread start") Thread.sleep(75) println("Thread end") }.start() }
Coroutines start immediately but suspend at delay; thread runs independently with sleep.
Both coroutines print start immediately. Coroutine 2 delays 50ms and ends first. Thread sleeps 75ms and ends after coroutine 2. Coroutine 1 delays 100ms and ends last.
Which reason best explains why Kotlin coroutines are often preferred over threads for concurrency?
Think about how coroutines simplify asynchronous programming and resource use.
Coroutines let you write code that looks like normal sequential code but runs asynchronously. They suspend without blocking threads, so they use less memory and are easier to manage than threads.