Kotlin – 等待function

kotlin有没有等待的function? (我不是指一个计时器计划,但实际上暂停执行)。 我读过,你可以使用Thread.sleep() 。 但是,它不适用于我,因为无法find函数。

线程睡眠总是需要等待多长时间: https : //docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#sleep( long )

 public static void sleep(long millis) throws InterruptedException 

例如

 Thread.sleep(1_000) // wait for 1 second 

如果你想等一些其他线程来唤醒你,也许`对象#等待()“会更好

https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait()

 public final void wait() throws InterruptedException 

然后另一个线程必须调用yourObject#notifyAll()

例如Thread1和Thread2共享一个Object o = new Object()

 Thread1: o.wait() // sleeps until interrupted Thread2: o.notifyAll() // wake up ALL waiting Threads of object o 

请试试这个将适用于Android。

  Handler().postDelayed({ // This method will be executed once the timer is over }, 1000) } 

由于Kotlin版本1.1中提供了新的协程function,所以您可以使用非阻塞 delayfunction和这样的签名:

suspend fun delay(time: Long, unit: TimeUnit = TimeUnit.MILLISECONDS)

在Kotlin 1.2中它仍然位于kotlinx.coroutines.experimental包中。 这里描述了协程的实验状态。