![]() |
儒雅的热带鱼 · 库克教师节送问候,网友的互动才是亮点|苹果| ...· 7 月前 · |
![]() |
帅气的青蛙 · openwrt-koolshare-mod- ...· 8 月前 · |
![]() |
重情义的鸵鸟 · 火影忍者中12小强里实力排名是怎样的? - 知乎· 1 年前 · |
![]() |
没有腹肌的麦片 · 兄不友弟不恭完整,在线全集,漫画类型 - 快看漫画· 1 年前 · |
![]() |
奔跑的香烟 · open-vm-tools包与vmware ...· 1 年前 · |
我需要实现一个函数,在点击一个按钮60秒后运行。请帮帮忙,我使用了Timer类,但我认为这不是最好的方法。
您应该使用
Thread.sleep()
方法。
try {
Thread.sleep(60000);
callTheFunctionYouWantTo();
} catch(InterruptedException ex) {
}
这将等待60,000毫秒(60秒),然后执行代码中的下一条语句。
您可以简单地使用
Thread.sleep()
来实现此目的。但是,如果您在具有用户界面的多线程环境中工作,则需要在单独的线程中执行此操作,以避免睡眠阻塞用户界面。
try{
Thread.sleep(60000);
// Then do something meaningful...
}catch(InterruptedException e){
e.printStackTrace();
}
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);
}
该函数将在100ms内使用新线程启动。
不要使用
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);
它在60秒后从scheduleAtFixedRate https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html 运行