我需要创建一个对象,该对象将使用自己的类方法停止执行一段时间。如何让程序跟踪流逝的时间并在指定的时间量过去时执行函数。
我想...
long pause; //a variable storing pause length in milliseconds.............
long currentTime; // which store the time of execution of the pause ,.............
当另一个变量跟踪时间的值与当前时间 + 暂停相同时,将执行下一行代码。 是否有可能创建一个变量,随着时间的推移,在短时间内每毫秒变化一次?
对于一个简单的解决方案,您可以使用Thread#sleep
public void waitForExecution(long pause) throws InterruptedException {
// Perform some actions...
Thread.sleep(pause);
// Perform next set of actions
}
带计时器...
public class TimerTest {
public static void main(String[] args) {
Timer timer = new Timer("Happy", false);
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("Hello, I'm from the future!");
}
}, 5000);
System.out.println("Hello, I'm from the present");
}
}
并带有循环
long startAt = System.currentTimeMillis();
long pause = 5000;
System.out.println(DateFormat.getTimeInstance().format(new Date()));
while ((startAt + pause) > System.currentTimeMillis()) {
// Waiting...
}
System.out.println(DateFormat.getTimeInstance().format(new Date()));
请注意,这比其他两种解决方案更昂贵,因为循环继续消耗 CPU 周期,而Thread#sleep
和Timer
使用内部调度机制,允许线程空闲(而不是消耗周期)