在java中是否有Thread.sleep的替代品

这是我的代码

while (true) { try { Thread.sleep(5 * 60 * 1000); processData();// data processing job } catch (InterruptedException e) { SystemMessageBillPay.getInstance().writeMessage("ERROR: CEB.run() - " + e.getMessage()); } catch (NumberFormatException e) { SystemMessageBillPay.getInstance().writeMessage("ERROR: CEB.run() - " + e.getMessage()); } } 

对此

“Thread.sleep(5 * 60 * 1000);”

代码检查员发出警告

“在循环中调用Thread.sleep会导致性能问题”

什么应该是防止此警告的代码

 Is there a alternative to Thread.sleep 

是的,有方法。 但是

看起来你想安排一些工作。 您可以使用TimerTask或ScheduledExecutorService代替此。 所以后面的部分问题是关于

“在循环中调用Thread.sleep会导致性能问题”

这将通过安排任务来解决。

安排任务。

 public class Test extends TimerTask{ public static void main(String[] args) { Test task = new Test(); Timer timer = new Timer(); Calendar today = Calendar.getInstance(); today.set(Calendar.HOUR_OF_DAY, 13); today.set(Calendar.MINUTE, 47); today.set(Calendar.SECOND, 0); timer.schedule(task, today.getTime(), TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS)); } @Override public void run() { System.out.println("Running Scheduled Task...!!!"); } } 

您需要为此任务使用秒表计时器而不是线程。 使用:org.apache.commons.lang.time.StopWatch在这里描述: http : //commons.apache.org/lang/

或者你使用石英。 它是一个外部库:

http://www.quartz-scheduler.org/