Java中的javascript setTimeout相当于什么?
我需要实现一个函数,在单击按钮60秒后运行。 请帮助,我使用了Timer类,但我认为这不是最好的方法。
“我使用了Timer类,但我认为这不是最好的方法。”
其他答案假设您没有使用Swing作为您的用户界面(按钮)。
如果您使用的是Swing,请不要使用Thread.sleep()
因为它会冻结您的Swing应用程序。
相反,你应该使用javax.swing.Timer
。
有关更多信息和示例,请参阅Java教程如何使用Swing Timers和Lesson:Swurrency中的并发 。
使用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(); }
要使用lambda表达式调用:
setTimeout(() -> System.out.println("test"), 1000);
或者使用方法参考:
setTimeout(anInstance::aMethod, 1000);
要处理当前运行的线程,只使用同步版本:
public static void setTimeoutSync(Runnable runnable, int delay) { try { Thread.sleep(delay); runnable.run(); } catch (Exception e){ System.err.println(e); } }
在主线程中谨慎使用它 – 它将在调用之后挂起所有内容,直到timeout
到期并且runnable
执行。
您可以简单地使用Thread.sleep()
来实现此目的。 但是,如果您在具有用户界面的multithreading环境中工作,则需要在单独的线程中执行此操作以避免睡眠阻止用户界面。
try{ Thread.sleep(60000); // Then do something meaningful... }catch(InterruptedException e){ e.printStackTrace(); }
不要使用Thread.sleep
,否则它将冻结你的主线程,而不是从JS模拟setTimeout。 您需要创建并启动一个新的后台线程来运行代码,而不必停止执行主线程。 喜欢这个:
new Thread() { @Override public void run() { try { this.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } // your code here } }.start();
您应该使用Thread.sleep()
方法。
try { Thread.sleep(60000); callTheFunctionYouWantTo(); } catch(InterruptedException ex) { }
这将等待60,000毫秒(60秒),然后执行代码中的下一个语句。
public ScheduledExecutorService = ses; ses.scheduleAtFixedRate(new Runnable(){ run(){ //running after specified time } }, 60, TimeUnit.SECONDS);
从scheduleAtFixedRate开始60秒后运行https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html
underscore-java库中有setTimeout()
方法。
代码示例:
import com.github.underscore.U; import com.github.underscore.Function; public class Main { public static void main(String[] args) { final Integer[] counter = new Integer[] {0}; Function incr = new Function () { public Void apply() { counter[0]++; return null; } }; U.setTimeout(incr, 100); } }
该函数将在100ms内以新线程启动。