为了账号安全,请及时绑定邮箱和手机立即绑定

每X秒打印一次“ hello world”

每X秒打印一次“ hello world”

catspeake 2019-10-25 14:52:55
最近我一直在使用带有大量数字的循环来打印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秒打印一次?
查看完整描述

3 回答

?
炎炎设计

TA贡献1808条经验 获得超4个赞

您还可以查看Timer和TimerTask类,这些类可用于计划任务每秒钟运行一次n。


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


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


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


查看完整回答
反对 回复 2019-10-25
?
慕莱坞森

TA贡献1810条经验 获得超4个赞

如果要执行定期任务,请使用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);


查看完整回答
反对 回复 2019-10-25
  • 3 回答
  • 0 关注
  • 628 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信