每隔5秒运行一次代码是不是很糟糕?

use*_*452 0 java loops

我希望我的代码每5秒运行一次,例如使用:

    try {
        Thread.sleep(5000);
    } catch (InterruptedException ie) {
          //Handle exception
    }
Run Code Online (Sandbox Code Playgroud)

然而,while围绕这个做一个循环是不是很糟糕的做法,总是每隔5秒发生一次,或者这样可以吗?

Tho*_*lut 5

使用预定的执行程序:

ScheduledExecutorService pool = Executors.newScheduledThreadPool(4);
pool.scheduleAtFixedRate(() -> { System.out.println("Hello World"); }, 0l, 5l, TimeUnit.SECONDS);
Run Code Online (Sandbox Code Playgroud)

单击以查看ScheduledExecutorService的文档.