A thread is the JVM’s classic unit for running code independently and concurrently. Kotlin remains fully compatible with Java threads and provides a convenient thread function for starting one. section 14.3
import kotlin.concurrent.thread
fun main() {
println("I'm on ${Thread.currentThread().name}")
thread { #1
println("And I'm on ${Thread.currentThread().name}")
}
}
// I'm on main
// And I'm on Thread-0
Start on the main thread, create a second thread with Kotlin’s thread function, and print each thread’s name. section 14.3
Threads can improve responsiveness and distribute work across multicore CPUs, but each JVM thread typically maps to an operating-system thread. Allocation, kernel-level switching, and memory use make threads costly; only a few thousand can usually be managed effectively. section 14.3
Treat threads carefully when work waits or must be coordinated:
- A thread blocked on a network request cannot perform other meaningful work while waiting. section 14.3
- Fine-grained or short-lived thread creation is discouraged because creation and management costs accumulate. section 14.3
- Standalone threads make cancellation, exception handling, and work orchestration harder to manage. section 14.3
Blocking network logic
A sequential showUserInfo function calls login, loadUserData, and showData. If the first two calls wait on the network, the underlying thread remains blocked, limiting request capacity or freezing a user interface. section 14.4.1
Coroutines address this limitation with suspending functions. Marking the network-related functions suspend lets execution pause without blocking the underlying thread, allowing other code to run on it while the response is pending. section 14.4.1











