【问题标题】:timer implementation in java [duplicate]java中的计时器实现[重复]
【发布时间】:2015-11-18 07:54:40
【问题描述】:

提示用户输入秒数,然后每秒显示一条消息,并在时间到期时终止的​​程序。到目前为止,我已经能够做到这一点。但是,我被困在这里了。

public static void main(String[] args) 
    {
    Scanner r = new Scanner(System.in); 
        int sec = r.nextInt(); 
        while (sec > 0)
        { 
            System.out.println("Seconds Remaining" + sec); 
            /**What to do here using System.currentTimeMillis()??**/ 
            sec--;
        }
}

【问题讨论】:

  • 我很确定到目前为止它们还没有被覆盖。有没有别的办法?? @Reimeus
  • docs.oracle.com/javase/tutorial/essential/concurrency/… 文档中的示例与您的几乎相同...
  • 您还可以进行旋转循环并检查开始时间和当前时间之间的差异。不是我会推荐它,但如果你没有了解线程..

标签: java timer


【解决方案1】:

从“我怎样才能在选定的方法(使用 currentTimeMillis)内完成这项工作,这对于学习有一定的价值,因此下次我需要做类似的事情,这是我不会做的正确方法卡住了,尽管这一次不是最好的方法”的观点:

long start = System.currentTimeMillis();
long now = System.currentTimeMillis();
while (now - start > 1000) // While the difference between the two times is less than a second
{
    now = System.currentTimeMillis();
}

您甚至可以尝试纠正错误(now-start-1000 毕竟可能大于 1,这会浪费时间)并计算任何多余的时间。然后,您将取出多余的部分并将其从循环条件中的 1000 中减去,这样下一次您将等待更少的时间来弥补上次的多余部分。此外,System.out.println() 需要时间,因此您需要在System.out.println 之前设置 start 以便更准确一点。

现在,希望我已经指出了足够多的陷阱来证明为什么这对于任何重要的计时都是一个坏主意。更准确的最简单方法是使用Timer,它使用线程允许将打印和其他开销从计时中分离出来。但是,它只是对上述内容使用了一个不太有趣但更简单的解释,即Object.wait(),它“不提供实时保证”。

【讨论】:

  • 谢谢...解决了问题..“无论从哪个角度看”;)
【解决方案2】:

您正在寻找我怀疑的 Thread.sleep() 或 TimeUnit.sleep

public static void main(String[] args) throws InterruptedException {
    Scanner in = new Scanner(System.in); 
    for(int sec = in.nextInt(); sec > 0; sec --) {
        System.out.println("Seconds Remaining " + sec); 
        TimeUnit.SECONDS.sleep(1);
    }
}

【讨论】:

  • 是的,它的工作原理...唯一的问题是我还没有读到线程。不管怎么说,多谢拉。 :)
【解决方案3】:

使用线程是最合适的方式。

public static void main(String[] args) throws Exception 
{
    Scanner r = new Scanner(System.in); 
    int sec = r.nextInt(); 
    while (sec > 0)
    { 
        System.out.println("Seconds Remaining" + sec); 
        /**What to do here using System.currentTimeMillis()??**/ 
        Thread.sleep(1000);
        sec--;
    }
}

希望这会有所帮助:)

【讨论】:

  • 是的,它的工作原理......但我还没有读到关于线程的信息。不管怎么说,多谢拉。 :)
猜你喜欢
  • 2017-06-06
  • 2016-11-22
  • 2012-11-07
  • 1970-01-01
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
  • 2012-12-22
  • 2010-10-14
相关资源
最近更新 更多