java sleep 唤醒,Java Thread.sleep唤醒了“很多”消息。早于预定时间

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.

What could be the problem here?

Thanks

解决方案

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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值