在kotlin有等待功能吗?(我不是指计时器计划,但实际上暂停执行).我已经读过你可以使用了Thread.sleep().但是,它对我不起作用,因为无法找到该功能.
gue*_*ter 22
线程休眠总是需要等待多长时间:https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#sleep( long )
public static void sleep(long millis)
throws InterruptedException
Run Code Online (Sandbox Code Playgroud)
例如
Thread.sleep(1_000) // wait for 1 second
Run Code Online (Sandbox Code Playgroud)
如果你想等待其他一些Thread唤醒你,也许`Object#wait()'会更好
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait()
public final void wait()
throws InterruptedException
Run Code Online (Sandbox Code Playgroud)
然后另一个线程必须调用 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
Run Code Online (Sandbox Code Playgroud)
mur*_*glu 17
您可以使用 Kotlin 协程轻松实现这一点
class SplashActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
CoroutineScope(Dispatchers.IO).launch {
delay(TimeUnit.SECONDS.toMillis(3))
withContext(Dispatchers.Main) {
Log.i("TAG", "this will be called after 3 seconds")
finish()
}
}
Log.i("TAG", "this will be called immediately")
}
}
Run Code Online (Sandbox Code Playgroud)
build.gradle(应用程序)
dependencies {
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.1'
}
Run Code Online (Sandbox Code Playgroud)
Adi*_*hal 15
请试试这个,它适用于Android:
Handler().postDelayed(
{
// This method will be executed once the timer is over
},
1000 // value in milliseconds
)
Run Code Online (Sandbox Code Playgroud)
mco*_*ive 14
您可以使用标准JDK的东西.
之前的回复给出了Thread.sleep(millis: Long).我个人更喜欢TimeUnit类(从Java 1.5开始),它提供了更全面的语法.
TimeUnit.SECONDS.sleep(1L)
TimeUnit.MILLISECONDS.sleep(1000L)
TimeUnit.MICROSECONDS.sleep(1000000L)
Run Code Online (Sandbox Code Playgroud)
他们Thread.sleep在场景后面使用,他们也可以抛出InterruptedException.
| 归档时间: |
|
| 查看次数: |
41957 次 |
| 最近记录: |