Kotlin-等待功能

问题描述 投票:25回答:5

kotlin中是否有等待功能?(我不是说Timer Schedule,而是实际上暂停了执行)。我读过您可以使用Thread.sleep()。但是,它对我不起作用,因为找不到该函数。

kotlin wait
5个回答
22
投票

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

public static void sleep(long millis)
                  throws InterruptedException

e.g。

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

如果您想等待其他线程唤醒您,也许使用“ Object#wait()”会更好一些

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

public final void wait()
                throws InterruptedException

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

e.g。线程1和线程2共享一个Object o = new Object()

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

15
投票

请尝试此操作,它将适用于Android:

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

10
投票

您可以使用标准JDK的东西。

先前的回答为Thread.sleep(millis: Long)。我个人更喜欢TimeUnit类(从Java 1.5开始),它提供了更全面的语法。

TimeUnit.SECONDS.sleep(1L)
TimeUnit.MILLISECONDS.sleep(1000L)
TimeUnit.MICROSECONDS.sleep(1000000L)

他们在后台使用Thread.sleep,他们也可以引发InterruptedException。


10
投票

自从新的协程功能在Kotlin 1.1版中可用以来,您可以使用non-blocking delay函数并带有以下签名:

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

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

UPD: Kotlin 1.3已发布,协程已移至kotlinx.coroutines包中,它们不再是实验功能。

UPD 2:要在非可暂停方法中使用此方法,可以与其他任何可暂停方法一样,将其与runBlocking {}包围起来以使其阻塞

runBlocking {}

3
投票

您可以使用Kotlin协程轻松实现这一目标

© www.soinside.com 2019 - 2024. All rights reserved.