我需要创建一个对象,该对象将使用其自己的类方法在一定时间内停止执行。如何让程序跟踪时间的流逝并在经过指定的时间后执行函数。
我想……
long pause; //a variable storing pause length in milliseconds.............
long currentTime; // which store the time of execution of the pause ,.............
当另一个变量跟踪时间的值与 currentTime+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
使用内部调度机制允许线程空闲(并且不消耗周期)
关于java - 跟踪当前TimeMillis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13373403/