java - 跟踪当前TimeMillis

标签 java stopwatch

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

我想……

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#sleepTimer 使用内部调度机制允许线程空闲(并且不消耗周期)

关于java - 跟踪当前TimeMillis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13373403/

相关文章:

java - Spring集成疑问: CRUD operations and sharing events between components

Java线程并发

java - Spring Data MongoDB 集合聚合

c# - 我应该在读取 ElapsedMilliseconds 之前调用 Stop 吗?

c# - 将具有多个参数的函数作为参数传递

.net - .NET Stopwatch 类有这么糟糕吗?

java - 在一个线程中实现多个线程最有效的方法是什么?

java - Sonar 属性文件

c# - 32 位和 64 位 Windows 之间的日期时间粒度

java - 秒表 Java API