Kotlin - Wait function

OhMad picture OhMad · Jul 20, 2017 · Viewed 73.6k times · Source

Is there a wait function in kotlin? (I don't mean a Timer Schedule, but actually pause the execution). I have read that you can use Thread.sleep(). However, it doesn't work for me, because the function can't be found.

Answer

guenhter picture guenhter · Jul 20, 2017

Thread sleep always takes a time how long to wait: 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

If you want to wait for some other Thread to wake you, maybe `Object#wait()' would be better

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

public final void wait()
                throws InterruptedException

Then another thread has to call yourObject#notifyAll()

e.g. Thread1 and Thread2 shares an Object o = new Object()

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