打印“你好世界"每 X 秒 [英] Print "hello world" every X seconds

查看:21
本文介绍了打印“你好世界"每 X 秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Lately I've been using loops with large numbers to print out 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 秒打印一次?

I understand that this is a very silly way to do it, but I've never used any timer libraries in Java yet. How would one modify the above to print every say 3 seconds?

推荐答案

你也可以看看TimerTimerTask 类,可用于安排任务每 n 秒运行一次.

You can also take a look at Timer and TimerTask classes which you can use to schedule your task to run every n seconds.

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

You need a class that extends TimerTask and override the public void run() method, which will be executed everytime you pass an instance of that class to timer.schedule() method..

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

Here's an example, which prints Hello World every 5 seconds: -

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);

这篇关于打印“你好世界"每 X 秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆