如何向此类添加暂停和恢复方法? 当你暂停并且它已经暂停时,什么都不会发生。 此外,如果您在未暂停时恢复,则不会发生任何事情。
public class Stopwatch {
private final long start;
public Stopwatch() {
start = System.currentTimeMillis();}
public double elapsedTime() {
long now = System.currentTimeMillis();
return (now - start) / 1000.0;}
public static void main(String[] args) {
Stopwatch watch = new Stopwatch();
double total = 0.0;
for (int i = 0; i < 100000000; i++)
total += Math.random();
double time = watch.elapsedTime();
StdOut.println(time);
}
}
最佳答案
为什么不保存一个变量 accumulatedTime
并在调用 pause()
方法时将累积时间附加到它
accumulatedTime += System.currentTimeMillis() - start / 1000.0;
当调用 resume()
时,您可以重置开始
start = System.currentTimeMillis();
然后 elapsedTime()
会将两者相加:
public double elapsedTime() {
long now = System.currentTimeMillis();
return ((now - start) / 1000.0) + accumulatedTime;
}
您还需要跟踪暂停状态 - 也许是一个 isPaused
boolean
实例变量?然后您的 pause()/resume()
可以在适当的情况下做出响应
例如在 pause()
方法中:
if (isPaused) {
return; //do nothing
}
关于java - 向秒表类添加暂停和恢复方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58983710/