我想推迟做某事,类似于设置一个倒计时定时器,在一定时间后“执行某个动作”。
我希望在等待的同时,程序的其余部分能够继续运行,因此我尝试创建一个包含一分钟延迟的自己的 Thread
:
public class Scratch {
private static boolean outOfTime = false;
public static void main(String[] args) {
Thread countdown = new Thread() {
@Override
public void run() {
try {
// wait a while
System.out.println("Starting one-minute countdown now...");
Thread.sleep(60 * 1000);
// do the thing
outOfTime = true;
System.out.println("Out of time!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
countdown.start();
while (!outOfTime) {
try {
Thread.sleep(1000);
System.out.println("do other stuff here");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
虽然这种方法勉强可行,但似乎应该有更好的方法。
经过一些搜索,我发现了一些类似的问题,但它们并没有真正解决我想做的事情:
我不需要这么复杂的东西,我只想在一定时间后完成一个单一的任务,而让程序的其余部分继续运行。
我应该如何安排一次性任务来“做一件事”?
schedule()
方法中的时间是动作运行之前的延迟时间。 - azurefrogcountdown
对象从这里提供的TimeUnit
获取1分钟的值。如何修改此代码以每1分钟连续运行?我的意思是与您现在的代码行为完全相反。 - Suresh