What is the equivalent of javascript setTimeout in

2020-02-07 19:07发布

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条回答
男人必须洒脱
2楼-- · 2020-02-07 19:24

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.

查看更多
贼婆χ
3楼-- · 2020-02-07 19:29

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.

try{
    Thread.sleep(60000);
    // Then do something meaningful...
}catch(InterruptedException e){
    e.printStackTrace();
}
查看更多
家丑人穷心不美
4楼-- · 2020-02-07 19:29

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();
查看更多
登录 后发表回答