我需要实现一个函数,在单击按钮60秒后运行。请帮助,我使用了Timer类,但我认为这不是最好的方法。
答案 0 :(得分:30)
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
执行。
答案 1 :(得分:20)
“我使用了Timer类,但我认为这不是最好的方法。”
其他答案假设您没有使用Swing作为用户界面(按钮)。
如果您使用Swing,请执行不使用Thread.sleep()
,因为它会冻结您的Swing应用程序。
相反,您应该使用javax.swing.Timer
。
有关更多信息和示例,请参阅Java教程How to Use Swing Timers和Lesson: Concurrency in Swing。
答案 2 :(得分:6)
您可以简单地使用Thread.sleep()
来达到此目的。但是,如果您在具有用户界面的多线程环境中工作,则需要在单独的线程中执行此操作以避免睡眠阻止用户界面。
try{
Thread.sleep(60000);
// Then do something meaningful...
}catch(InterruptedException e){
e.printStackTrace();
}
答案 3 :(得分:5)
使用Java 9 CompletableFuture,每一个简单的方法:
CompletableFuture.delayedExecutor(5, TimeUnit.SECONDS).execute(() -> {
// Your code here executes after 5 seconds!
});
答案 4 :(得分:3)
不要使用Thread.sleep
或者它会冻结你的主线程而不是模拟来自JS的setTimeout。您需要创建并启动一个新的后台线程来运行代码,而不必停止执行主线程。像这样:
new Thread() {
@Override
public void run() {
try {
this.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// your code here
}
}.start();
答案 5 :(得分:1)
您应该使用Thread.sleep()
方法。
try {
Thread.sleep(60000);
callTheFunctionYouWantTo();
} catch(InterruptedException ex) {
}
这将等待60,000毫秒(60秒),然后执行代码中的下一个语句。
答案 6 :(得分:1)
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<Void> incr = new Function<Void>() { public Void apply() {
counter[0]++; return null; } };
U.setTimeout(incr, 100);
}
}
使用新线程将在100ms内启动该功能。
答案 7 :(得分:1)
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
答案 8 :(得分:0)
new Timer().schedule(new TimerTask() {
@Override
public void run() {
// here goes your code to delay
}
}, 300L); // 300 is the delay in millis
Here,您可以找到一些信息和示例。