0
0
Kotlinprogramming~5 mins

Delay vs Thread.sleep in Kotlin

Choose your learning style9 modes available
Introduction

We use delays to pause actions in programs. Delay is for suspending without blocking, while Thread.sleep blocks the thread completely.

When you want to pause a coroutine without stopping other tasks.
When you need to wait in a simple program and don't mind blocking the thread.
When writing asynchronous code that should stay responsive.
When simulating a wait time in a background task.
When you want to freeze the whole thread for a fixed time.
Syntax
Kotlin
suspend fun delay(timeMillis: Long)

fun Thread.sleep(timeMillis: Long)

delay is a suspend function used inside coroutines.

Thread.sleep is a blocking call that stops the current thread.

Examples
This example shows delay inside a coroutine. It pauses without blocking the thread.
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    println("Start delay")
    delay(1000L) // pauses coroutine for 1 second
    println("End delay")
}
This example uses Thread.sleep which blocks the whole thread for 1 second.
Kotlin
fun main() {
    println("Start sleep")
    Thread.sleep(1000) // blocks thread for 1 second
    println("End sleep")
}
Sample Program

This program shows both delay and Thread.sleep. The first pauses inside a coroutine without blocking. The second blocks the thread.

Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    println("Before delay")
    delay(500L)
    println("After delay")
}

fun blockingSleep() {
    println("Before sleep")
    Thread.sleep(500)
    println("After sleep")
}

fun mainBlocking() {
    blockingSleep()
}

// Run coroutine example
main()
// Run blocking example
mainBlocking()
OutputSuccess
Important Notes

delay requires a coroutine context to work.

Thread.sleep can freeze your app if used on the main thread.

Use delay for smooth, responsive apps and Thread.sleep for simple blocking waits.

Summary

delay pauses coroutines without blocking threads.

Thread.sleep blocks the current thread completely.

Prefer delay in asynchronous Kotlin code for better performance.