why can't i cancel job in kotlin coroutines?

Viewed 302

this is when I use the delay function

    @Test
    fun testJob(){
        runBlocking {
            val job = GlobalScope.launch {
                println("Start Coroutine ${Date()}")
                delay(1000)
                println("End Coroutine ${Date()}")
            }
            job.cancel()
            delay(2000)
        }
    }

this is when i use the Thread.sleep function

    @Test
    fun testJob(){
        runBlocking {
            val job = GlobalScope.launch {
                println("Start Coroutine ${Date()}")
                Thread.sleep(1000)
                println("End Coroutine ${Date()}")
            }
            job.cancel()
            delay(2000)
        }
    }

why cancel() can't work when i use Thread.sleep ?

2 Answers

Thread.sleep() is a blocking method, while delay() is a suspend one. Kotlin coroutines may run on a single thread asynchronously, there is a state machine inside, which switches between suspend calls, but when you call Thread.sleep(), it blocks the entire thread.

delay()'s doc says: "Delays coroutine for a given time without blocking a thread and resumes it after a specified time." But when you call Thread.sleep(), you are delaying the thread itself, which prevents everything else from running on that thread, even other coroutines.

Related