【问题标题】:How to set a timer in java in a non swing/database application如何在非 Swing/数据库应用程序中的 Java 中设置计时器
【发布时间】:2014-05-17 14:36:27
【问题描述】:

是否可以在 Java 控制台应用程序中制作一个以秒为单位倒计时的计时器?那么可以说数10秒吗?打印一份声明;再数 10 秒并打印另一条语句等。如果是这样,我该怎么做?

【问题讨论】:

标签: java class timer


【解决方案1】:
    // This is how to print with a delay
    // Thread.sleep stops the program executoin for an amount of time
    System.out.println("String 1");


    try {
        Thread.sleep(1000);  // Thread.sleep takes in milliseconds
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println("String 2");

    // This is how to count down with a delay. Its accuracy is questionable, because
    // printing and increminting k take time, but it should be very close to a second.
    for(int k = 10; k > 0; k--)
    {
        System.out.println(k);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

【讨论】:

  • 它停止线程,在这种情况下,程序停止数毫秒。查看Thread.Sleep的java文档
猜你喜欢
  • 2011-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-17
  • 1970-01-01
相关资源
最近更新 更多