Last active
April 21, 2021 23:42
-
-
Save Shilo/207c7ba4a604b7811b77ff17be8580f3 to your computer and use it in GitHub Desktop.
Java "setTimeout" equivalent. (Credit: Oleg Mikhailov, http://stackoverflow.com/a/36842856)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Asynchronous implementation with JDK 1.8: | |
public static void setTimeout(Runnable runnable, int delay){ | |
new Thread(() -> { | |
try { | |
Thread.sleep(delay); | |
runnable.run(); | |
} | |
catch (Exception e){ | |
System.err.println(e); | |
} | |
}).start(); | |
} | |
// To call with lambda expression: | |
setTimeout(() -> System.out.println("test"), 1000); | |
// Or with method reference: | |
setTimeout(anInstance::aMethod, 1000); | |
// To deal with the current running thread only use a synchronous version: | |
public static void setTimeoutSync(Runnable runnable, int delay) { | |
try { | |
Thread.sleep(delay); | |
runnable.run(); | |
} | |
catch (Exception e){ | |
System.err.println(e); | |
} | |
} | |
//Use this with caution in main thread – it will suspend everything after the call until timeout expires and runnable executes. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment