每 X 秒打印“hello world”

新手上路,请多包涵

最近我一直在使用大量循环来打印出 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 秒打印一次?

原文由 meiryo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 729
2 个回答

您还可以查看 TimerTimerTask 类,您可以使用这些类来安排您的任务每隔 n 秒运行一次。

您需要一个扩展 TimerTask 并覆盖 public void run() 方法的类,每次将该类的实例传递给 timer.schedule() 方法时都会执行该方法。

这是一个示例,每 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);

原文由 Rohit Jain 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果要执行周期性任务,请使用 ScheduledExecutorService 。具体 ScheduledExecutorService.scheduleAtFixedRate

编码:

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

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

原文由 Tim Bender 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏