gpt4 book ai didi

java - 向秒表类添加暂停和恢复方法

转载 作者:行者123 更新时间:2023-12-01 20:07:00 25 4
gpt4 key购买 nike

如何向此类添加暂停和恢复方法?当你暂停并且它已经暂停时,什么都不会发生。此外,如果您在未暂停时恢复,则不会发生任何事情。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com