【问题标题】:Handling java stopwatch start and stop errors处理java秒表启动和停止错误
【发布时间】:2014-07-10 14:17:00
【问题描述】:

如您所知,如果您在 org.apache.commons.lang3 类中尝试 .start() 一个已经启动的秒表,它会崩溃,说它已经启动。停止它也是如此。 有没有更简洁的方法(除了try catch)来处理这个问题。有点像在 c# 中,如果秒表已经开始,它会忽略该语句。 我在 LibGDX 框架上的音效也遇到了这个问题。 有任何想法吗? 非常感谢!

【问题讨论】:

  • 你能发布一些示例代码吗?堆栈跟踪? “如你所知”是什么意思?
  • 秒表可能不是用于此目的的最佳类,毕竟如果您不知道秒表是否/何时启动,那么它有什么用?可能还有其他类,例如 Timer 更适合您的需求。
  • 对你的回答有帮助吗?

标签: java stopwatch


【解决方案1】:

查看the docs of getTime()

如果手表没有启动,该方法应该返回0。探索the source code 以验证:

public long getTime() {
    if (this.runningState == STATE_STOPPED || this.runningState == STATE_SUSPENDED) {
        return this.stopTime - this.startTime;
    } else if (this.runningState == STATE_UNSTARTED) {
        return 0;
    } else if (this.runningState == STATE_RUNNING) {
        return System.currentTimeMillis() - this.startTime;
    }
    throw new RuntimeException("Illegal running state has occured. ");
}

所以你可以使用它,而不是 try-catch:

if(watch.getTime() == 0L) {
    watch.start();
}

if(watch.getTime() > 0L) {
    watch.stop();
}

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2011-10-26
    • 2015-04-27
    • 2020-10-13
    • 1970-01-01
    • 2012-11-06
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多