kotlin: delay和sleep的区别:

一,代码:

        binding.button1.setOnClickListener {

            println("sleep1 start,") // 协程已在等待时主线程还在继续
            Thread.sleep(200L)     // 阻塞主线程 0.2 秒钟
            println("sleep1 end,") // 协程已在等待时主线程还在继续

            GlobalScope.launch { // 在后台启动一个新的协程并继续
                println("suspend start!") // 在延迟后打印输出
                delay(1000L) // 非阻塞的等待 1 秒钟(默认时间单位是毫秒)
                println("suspend end!") // 在延迟后打印输出
            }

            println("sleep2 start,") // 协程已在等待时主线程还在继续
            Thread.sleep(2000L)     // 阻塞主线程 2 秒钟
            println("sleep2 end,") // 协程已在等待时主线程还在继续


        }

说明:

delay不会阻塞当前线程,而是会交出CPU时间去执行其他代码,
       即: 协程会被挂起但不会占用线程资源,其他协程可继续执行
sleep会阻塞当前线程,导致线程无法执行其他任务,直到休眠时间结束。

二,测试效果:

2025-07-15 15:43:20.220 10823-10823 System.out              com.example.okdemo1                  I  sleep1 start,
2025-07-15 15:43:20.422 10823-10823 System.out              com.example.okdemo1                  I  sleep1 end,
2025-07-15 15:43:20.529 10823-10823 System.out              com.example.okdemo1                  I  sleep2 start,
2025-07-15 15:43:20.537 10823-10874 System.out              com.example.okdemo1                  I  suspend start!
2025-07-15 15:43:21.554 10823-10874 System.out              com.example.okdemo1                  I  suspend end!
2025-07-15 15:43:22.531 10823-10823 System.out              com.example.okdemo1                  I  sleep2 end,

 

posted @ 2025-07-19 07:47  刘宏缔的架构森林  阅读(39)  评论(0)    收藏  举报