Sobes.tech
Junior — Middle

How is interaction and execution of two coroutines within a single thread performed?

sobes.tech AI

Answer from AI

In Kotlin, coroutines within the same thread of execution (for example, Dispatchers.Main or Dispatchers.Default) operate based on cooperative multitasking. This means that coroutines do not forcibly interrupt each other, but voluntarily yield control by calling special suspension points (suspend functions).

When a coroutine reaches a suspension point, it saves its state and releases the thread, allowing another coroutine to run. Thus, multiple coroutines can efficiently share a single thread, executing alternately without blocking.

Example:

import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        repeat(3) {
            println("Coroutine 1: $it")
            delay(100) // suspends the coroutine, freeing the thread
        }
    }
    launch {
        repeat(3) {
            println("Coroutine 2: $it")
            delay(100)
        }
    }
}

Here, both coroutines run on the same thread, taking turns yielding control to each other when calling delay.