【问题标题】:How to set delay in Kotlin?如何在 Kotlin 中设置延迟?
【发布时间】:2022-06-10 20:24:54
【问题描述】:

我只想等两三秒,我知道用Java怎么做,我试过了,但不知道kotlin

一些简单的东西:

println("hello")
// a 2 seconds delay
println("world")

【问题讨论】:

  • 你尝试了什么?发生了什么?

标签: android kotlin


【解决方案1】:

这很简单。只需使用协程即可。像这样:

fun main() = runBlocking { 
    launch { 
        delay(2000L)
        println("World!") 
    }
    println("Hello")
}

不要忘记像这样导入 kotlin 协程:

import kotlinx.coroutines.*

在 kotlin 中编码愉快!!!

【讨论】:

    【解决方案2】:

    有一些方法:

    1- 使用处理程序(基于毫秒)(已弃用):

    println("hello")
    Handler().postDelayed({
       println("world")
    }, 2000)
    

    2- 使用执行器(基于秒):

    println("hello")
    Executors.newSingleThreadScheduledExecutor().schedule({
        println("world")
    }, 2, TimeUnit.SECONDS)
    

    3- 使用定时器(基于毫秒):

    println("hello")
    Timer().schedule(2000) {
      println("world")
    }
    

    【讨论】:

      【解决方案3】:

      如果您不想使用任何依赖项,则可以使用Thread.sleep(2000L) 这里,1 秒 = 1000L 代码应该是这样的,

      println("hello")
      Thread.sleep(2000L)
      println("world")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-30
        • 1970-01-01
        • 1970-01-01
        • 2019-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-26
        相关资源
        最近更新 更多