Java Thread.sleep唤醒了“很多"消息.早于预定时间 [英] Java Thread.sleep waking up "much" earlier than the scheduled time

查看:224
本文介绍了Java Thread.sleep唤醒了“很多"消息.早于预定时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个守护程序,该守护程序启动在不同时间唤醒的线程数.该守护程序使用Commons apache库用Java编写,并在Linux机器(Fedora 13)上运行. 每天都有一个线程唤醒以执行按计划执行的任务A. 但是还有另一个线程计划在每个星期一的早上6点醒来,以执行某些未按计划进行的任务.问题在于该线程在实际的计划时间之前醒来了.尽管应该只在一周后运行,但它在上一次运行完成后的两天后才运行.等待时间是使用我们自己的计时器类正确计算的,因为它可以重用现有代码,所以我看不到任何问题.

I have a requirement of writing a daemon which initiates number of threads that wakes up at different times. The daemon is written in Java using commons apache library and is run on a Linux machine (Fedora 13 ). One thread wakes up everyday to perform task A which happens as scheduled. But there is another thread which is scheduled to wake up every Monday at 6 am to perform some task which does not happen as scheduled. The problem is that this thread wakes up much before the actual scheduled time. It runs 2 days after the completion of the previous run though it should run only after a week. The waiting time is calculated correctly using our own timer class and because this reuses existing code i do not see a problem in this.

这里可能是什么问题?

谢谢

推荐答案

Thread.sleep()不做任何保证,它可能比预期的早起.您应该始终在循环中使用它:

Thread.sleep() doesn't make any guarantees, and it might wake up earlier than expected. you should always use it in the loop:

long curTime = System.currentTimeMillis();

while (wakeUpTime - curTime > 0) {
  try {
    Thread.sleep(wakeUpTime - curTime);
  } catch (InterruptedException ex) { }
  curTime = System.currentTimeMillis();
}

这篇关于Java Thread.sleep唤醒了“很多"消息.早于预定时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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