每隔X秒打印"hello world"

mei*_*ryo 119 java timer

最近我一直在使用大数字循环打印出来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++;
}
Run Code Online (Sandbox Code Playgroud)

我知道这是一个非常愚蠢的方法,但我还没有在Java中使用任何计时器库.怎么会修改上面打印每说3秒?

Tim*_*der 184

如果要执行定期任务,请使用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);
Run Code Online (Sandbox Code Playgroud)

  • 我希望其他人也支持这一点.Thread.sleep()可能最适合OP中的代码,但它是一个相当业余的轮子改造.专业软件工程师将使用经过尝试和信任的API,例如TimerTask.但是,ScheduledExecutorService甚至更好; 请参阅Brian Goetz等人的_Java Concurrency in Practice_.后一类已经存在了近十年 - 令人遗憾的是,所有这些其他答案都忽略了它. (9认同)
  • @MichaelScheper,谢谢,我很高兴看到这个答案终于超越了`TimerTask`变体.有趣的是,我注意到接受的答案实际上并不正确:\除了两个API的年龄,`ScheduledExecutorService`只是更直观的声明.使用"TimeUnit"作为参数可以更清楚地了解正在发生的事情.像"5*60*1000 // 5分钟"这样的代码日子已经一去不复返了. (2认同)
  • @TimBender我注意到你有一个3为期间参数.我无法确定是在几秒或几毫秒.我想让它每500毫秒(半秒)运行一次. (2认同)
  • 啊,我明白了.第四个参数允许您指定时间,例如TimeUnit.MILLISECONDS. (2认同)
  • @TerryCarter 在 Java8+ 中,您可以改为执行 `Runnable helloRunnable = () -&gt; { /*code */ };` 更漂亮;) (2认同)

Roh*_*ain 178

您还可以查看可用于安排任务每秒运行的类TimerTimerTaskn.

您需要一个扩展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);
Run Code Online (Sandbox Code Playgroud)

  • 请注意,2-param`chertage`方法将在指定的延迟后执行一次.需要使用3参数`schedule`或`scheduleAtFixedRate`. (7认同)
  • @TimBender只是想知道OP是否真的完成了他的任务;)无论如何,现在我更愿意使用`ExecutorService`来完成这些任务.与传统的Thread API相比,这确实是一个很大的改进.只是在回答时没用过它. (4认同)
  • `Timer timer = new Timer(true);`应该设置为'true`作为deamon.除非您希望在关闭应用程序后计时器仍在运行. (3认同)

小智 34

试着这样做:

Timer t = new Timer();
t.schedule(new TimerTask() {
    @Override
    public void run() {
       System.out.println("Hello World");
    }
}, 0, 5000);
Run Code Online (Sandbox Code Playgroud)

此代码将每隔5000毫秒(5秒)运行打印到控制台Hello World.有关详细信息,请阅读https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Timer.html


tmw*_*nik 14

我用计时器搞清楚了,希望它有所帮助.我从使用的计时器java.util.TimerTimerTask来自同一个包.见下文:

TimerTask task = new TimerTask() {

    @Override
    public void run() {
        System.out.println("Hello World");
    }
};

Timer timer = new Timer();
timer.schedule(task, new Date(), 3000);
Run Code Online (Sandbox Code Playgroud)


sau*_*m22 9

使用Thread.sleep(3000)进入looop

  • 我不喜欢这个解决方案,我认为这是一种解决方案,而不是真正的解决方案 (2认同)

Lui*_*oza 5

最简单的方法是将主线程设置为休眠 3000 毫秒(3 秒):

for(int i = 0; i< 10; i++) {
    try {
        //sending the actual Thread of execution to sleep X milliseconds
        Thread.sleep(3000);
    } catch(InterruptedException ie) {}
    System.out.println("Hello world!");
}
Run Code Online (Sandbox Code Playgroud)

这将使线程停止至少 X 毫秒。线程可能会休眠更多时间,但这取决于 JVM。唯一能保证的是线程将至少休眠那些毫秒。看看文档Thread#sleep

使当前正在执行的线程休眠(暂时停止执行)指定的毫秒数,具体取决于系统计时器和调度程序的精度和准确性

  • @meiryo 它将停止线程至少 X 毫秒。线程可能会休眠更多时间,但这取决于 JVM。唯一能保证的是线程将至少休眠那些毫秒。 (4认同)
  • 注意:如果这不是实时系统,则睡眠时间将至少为 3000 毫秒,但也可能更长。如果您想要正好 3000 毫秒的睡眠时间,尤其是在人命受到威胁的情况下(医疗器械、控制飞机等),您应该使用实时操作系统。 (4认同)

Vic*_*cky 5

public class HelloWorld extends TimerTask{

    public void run() {

        System.out.println("Hello World");
    }
}


public class PrintHelloWorld {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new HelloWorld(), 0, 5000);

        while (true) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                System.out.println("InterruptedException Exception" + e.getMessage());
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

创建无限循环,配置了广告调度程序任务。