如何在非swing/数据库应用程序中用java设置计时器

如何在非swing/数据库应用程序中用java设置计时器,java,class,timer,Java,Class,Timer,是否可以在Java控制台应用程序中创建以秒为单位的计时器?那么,是否可以说计数10秒;打印一份声明;再计算10秒,然后打印另一条语句等。如果是这样,我怎么做?它会停止线程,在本例中,程序会停止数毫秒。请看一下java文档,了解这是否有帮助 // This is how to print with a delay // Thread.sleep stops the program executoin for an amount of time System.out.prin

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

它会停止线程,在本例中,程序会停止数毫秒。请看一下java文档,了解这是否有帮助
    // 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();
        }

    }