What is the equivalent of javascript setTimeout in Java?

前端 未结 9 887
梦毁少年i
梦毁少年i 2020-12-13 06:23

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.

9条回答
  •  青春惊慌失措
    2020-12-13 06:42

    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:

    new Thread() {
        @Override
        public void run() {
            try {
                this.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
    
            // your code here
    
        }
    }.start();
    

提交回复
热议问题