|
|
帅气的酱牛肉 · 向荣:中世纪欧洲的海陆贸易与城市生活· 1 年前 · |
|
|
留胡子的鸵鸟 · 西播磨的四季- 春季| ...· 1 年前 · |
|
|
冲动的野马 · 2024华东师范大学881人文地理学考研复习 ...· 3 年前 · |
|
|
才高八斗的洋葱 · 张涵予:爆红后遭遇婚姻危机,现在他的家庭怎么 ...· 3 年前 · |
|
|
坚强的碗 · 堪萨斯大学惠荣庆教授高水平学术前沿讲座通知· 3 年前 · |
我需要实现一个函数,在点击一个按钮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 运行