Java中的javascript setTimeout相当于什么?

Aró*_*hez 33 javascript java timer settimeout setinterval

我需要实现一个函数,在单击一个按钮60秒后运行.请帮助,我使用了Timer类,但我认为这不是最好的方法.

Ole*_*lov 35

使用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();
}
Run Code Online (Sandbox Code Playgroud)

要使用lambda表达式调用:

setTimeout(() -> System.out.println("test"), 1000);
Run Code Online (Sandbox Code Playgroud)

或者使用方法参考:

setTimeout(anInstance::aMethod, 1000);
Run Code Online (Sandbox Code Playgroud)

要处理当前运行的线程,只使用同步版本:

public static void setTimeoutSync(Runnable runnable, int delay) {
    try {
        Thread.sleep(delay);
        runnable.run();
    }
    catch (Exception e){
        System.err.println(e);
    }
}
Run Code Online (Sandbox Code Playgroud)

在主线程中谨慎使用它 - 它将在调用之后暂停所有内容,直到timeout到期并runnable执行.


Dav*_*ill 21

"我使用了Timer类,但我认为这不是最好的方法."

其他答案假设您没有使用Swing作为您的用户界面(按钮).

如果您使用的是Swing,请不要使用,Thread.sleep()因为它会冻结您的Swing应用程序.

相反,你应该使用javax.swing.Timer.

有关更多信息和示例,请参阅Java教程如何使用Swing Timers和Lesson:Swurrency中的并发.


Luc*_*lli 8

使用java.util.Timer:

new Timer().schedule(new TimerTask() {
    @Override
    public void run() {
        // here goes your code to delay
    }
}, 300L); // 300 is the delay in millis
Run Code Online (Sandbox Code Playgroud)

在这里您可以找到一些信息和示例。

  • 谢谢,我还需要clearTimeout()替代方案,所以用法是...`Timer计时器= new Timer(); 计时器. 时间表(...); 计时器.取消();` (6认同)

Ama*_*tam 6

您可以简单地Thread.sleep()用于此目的.但是,如果您在具有用户界面的多线程环境中工作,则需要在单独的线程中执行此操作以避免睡眠阻止用户界面.

try{
    Thread.sleep(60000);
    // Then do something meaningful...
}catch(InterruptedException e){
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)


小智 6

不要使用,Thread.sleep否则它会冻结您的主线程并且不会从 JS 模拟 setTimeout。您需要创建并启动一个新的后台线程来运行您的代码,而不会停止主线程的执行。像这样:

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


        // your code here

    }
}.start();
Run Code Online (Sandbox Code Playgroud)


use*_*877 5

使用Java 9 CompletableFuture,每个简单的操作:

CompletableFuture.delayedExecutor(5, TimeUnit.SECONDS).execute(() -> {
  // Your code here executes after 5 seconds!
});
Run Code Online (Sandbox Code Playgroud)

  • 代码片段不起作用,它显示错误:CompletableFuture 类型的方法elastedExecutor(int, TimeUnit) 未定义 (2认同)