I need to implement a function to run after 60 seconds of clicking a button. Please help, I used the Timer class, but I think that that is not the best way.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Is there a limit to how many levels you can nest i
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- How to toggle on Order in ReactJS
Asynchronous implementation with JDK 1.8:
To call with lambda expression:
Or with method reference:
To deal with the current running thread only use a synchronous version:
Use this with caution in main thread – it will suspend everything after the call until
timeout
expires andrunnable
executes.You can simply use
Thread.sleep()
for this purpose. But if you are working in a multithreaded environment with a user interface, you would want to perform this in the separate thread to avoid the sleep to block the user interface.Do not use
Thread.sleep
or it will freeze your main thread and not simulate setTimeout from JS. You need to create and start a new background thread to run your code without stoping the execution of the main thread. Like this: