我需要实现一个函数,在点击按钮后60秒运行。请帮忙,我使用了Timer类,但我认为这不是最好的方法。
我需要实现一个函数,在点击按钮后60秒运行。请帮忙,我使用了Timer类,但我认为这不是最好的方法。
使用JDK1.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
执行完毕。
使用Java 9的CompletableFuture,非常简单:
CompletableFuture.delayedExecutor(5, TimeUnit.SECONDS).execute(() -> {
// Your code here executes after 5 seconds!
});
“我使用了Timer类,但我认为那不是最好的方法。”
其他回答假设您没有在Swing中使用用户界面(按钮)。
如果您正在使用Swing,则不要使用Thread.sleep()
,因为它会冻结您的Swing应用程序。
相反,您应该使用javax.swing.Timer
。
有关更多信息和示例,请参见Java教程如何使用Swing定时器以及Swing中的并发课程。
new Timer().schedule(new TimerTask() {
@Override
public void run() {
// here goes your code to delay
}
}, 300L); // 300 is the delay in millis
在这里,您可以找到一些信息和示例。
Timer timer = new Timer(); timer.schedule(...); timer.cancel();
- mikep您可以简单地使用 Thread.sleep()
来实现这个目的。但是,如果您正在使用带有用户界面的多线程环境,您将希望在单独的线程中执行此操作,以避免 sleep 阻塞用户界面。
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();
public ScheduledExecutorService = ses;
ses.scheduleAtFixedRate(new Runnable() {
run() {
//running after specified time
}
}, 60, TimeUnit.SECONDS);
它会在scheduleAtFixedRate
之后60秒运行。请查看ScheduledExecutorService文档。
Thread.sleep()
方法。try {
Thread.sleep(60000);
callTheFunctionYouWantTo();
} catch(InterruptedException ex) {
}
underscore-java库中有setTimeout()
方法。
代码示例:
import com.github.underscore.Underscore;
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
final Integer[] counter = new Integer[] {0};
Supplier<Void> incr =
() -> {
counter[0]++;
return null;
};
Underscore.setTimeout(incr, 0);
}
}
该函数将在100毫秒内启动一个新线程。