Junior — Middle
How do execution threads and coroutines differ from each other in the context of programming?
sobes.tech AI
Answer from AI
Execution threads are system scheduling units that allow code to run in parallel, using separate stacks and processor contexts. They are heavier to create and switch between, requiring synchronization for access to shared resources.
Coroutines are lightweight, cooperative execution units that operate within threads and enable writing asynchronous code sequentially. Coroutines do not create new threads; instead, they suspend and free the thread for other tasks, increasing efficiency.
Example in Kotlin:
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000L)
println("Coroutine completed")
}
println("Main thread")
}
Here, the coroutine does not block the main thread but suspends on delay, allowing other tasks to execute.