0

我需要创建一个对象,该对象将使用其自己的类方法在一定时间内停止执行。如何让程序跟踪经过的时间并在经过指定的时间后执行函数。

我想 .......

long pause; //a variable storing pause length in milliseconds.............
long currentTime; // which store the time of execution of the pause ,............. 

并且当另一个变量 tracking time 的值与 currentTime + pause 相同时,执行下一行代码。是否有可能使一个变量在短时间内随着时间的推移每毫秒变化一次?

4

1 回答 1

2

对于一个简单的解决方案,您可以使用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#sleepTimer使用允许线程空闲(而不消耗周期)的内部调度机制

于 2012-11-14T05:25:02.337 回答