每 X 秒打印“你好世界”

2022-08-31 07:41:31

最近我一直在使用带有大数字的循环来打印出来:Hello World

int counter = 0;

while(true) {
    //loop for ~5 seconds
    for(int i = 0; i < 2147483647 ; i++) {
        //another loop because it's 2012 and PCs have gotten considerably faster :)
        for(int j = 0; j < 2147483647 ; j++){ ... }
    }
    System.out.println(counter + ". Hello World!");
    counter++;
}

我知道这是一种非常愚蠢的方法,但我从未在Java中使用过任何计时器库。如何修改上述内容以每说3秒打印一次?


答案 1

如果要执行定期任务,请使用 .特别是 ScheduledExecutorService.scheduleAtFixedRateScheduledExecutorService

代码:

Runnable helloRunnable = new Runnable() {
    public void run() {
        System.out.println("Hello world");
    }
};

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(helloRunnable, 0, 3, TimeUnit.SECONDS);

答案 2

您还可以查看 TimerTimerTask 类,您可以使用它们来计划任务每秒运行一次。n

您需要一个扩展和重写该方法的类,每次您将该类的实例传递给 timer.schedule() method.时都会执行该类。TimerTaskpublic void run()

下面是一个示例,每 5 秒打印一次:-Hello World

class SayHello extends TimerTask {
    public void run() {
       System.out.println("Hello World!"); 
    }
}

// And From your main() method or any other method
Timer timer = new Timer();
timer.schedule(new SayHello(), 0, 5000);