【问题标题】:Make System.currentTimeMillis() stop counting?让 System.currentTimeMillis() 停止计数?
【发布时间】:2015-07-23 21:51:14
【问题描述】:

在我的代码中,我有一个在顶部运行的计时器,其值为System.currentTimeMillis()/1000.0。游戏开始时,名为tStart 的值被设置为System.currentTimeMillis,而当游戏结束时,名为tEnd 的值被设置为System.currentTimeMillis()。游戏结束时,时间值从System.currentTimeMillis() 更改为tEnd - tStart,但不是停留在一个值,而是继续计数。我该如何阻止它?

【问题讨论】:

  • 这个问题很难理解。你能提供一些代码示例吗?
  • 欢迎来到 SO。很遗憾,在您向我们提供 mcve 之前,我们无法为您提供帮助。
  • 你不能那样做。您应该将 tEnd - tStart 的值保存在变量中。

标签: java time


【解决方案1】:

您无法停止系统时钟。 你可以找到第三方秒表课程,可以做你想做的事。

Apache,它有org.apache.commons.lang.time.StopWatch

更一般地,您需要将 tStart 和 tEnd 保存到变量中,如果您需要再次启动计时器并将前一圈与新圈相关联,只需找到偏移量 (tStart2 - tEnd)

【讨论】:

    【解决方案2】:

    currentTimeMillis 以毫秒为单位显示当前时间。你不能让它停下来,只能读它。 你能显示你的代码吗?看起来这应该仍然有效。

    【讨论】:

    • 欢迎来到 SO。这种答案应该保留为 cmets。我知道你没有足够的声望离开 cmets,但这并不意味着你需要泛滥。添加一些代码和/或文档链接,使其更像答案。
    【解决方案3】:

    我想,你应该试着解释一下,你到底想什么时候收到。 为了最简单的目的,您可以使用 Stopwatch 的这个简单实现(并最终通过所需的功能扩展它的功能):

    public class Stopwatch {
    
        private long startTime;
        private long endTime;
        private boolean running;
    
        public Stopwatch(){
    
        }
    
        public void start(){
            this.startTime = System.nanoTime();
            running = true;
        }
    
        public void stop(){
            this.endTime = System.nanoTime();
            running = false;
        }
    
        public long getElapsedTime(){
            return (this.running ? System.nanoTime() : this.endTime) - this.startTime;
        }
    
        public boolean isRunning(){
            return this.running;
        }
    
        public void reset(){
            this.startTime = 0L;
            this.endTime = 0L;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-17
      • 1970-01-01
      • 2015-03-07
      • 1970-01-01
      相关资源
      最近更新 更多