Thread.sleep等待超过预期 [英] Thread.sleep waits more than expected

查看:117
本文介绍了Thread.sleep等待超过预期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码:

long msBefore = System.currentTimeMillis();
//Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
try
{Thread.sleep(200);
} catch (InterruptedException e){}
System.out.println("Time: " + (System.currentTimeMillis() - msBefore));

打印:

Time: 578
Time: 594
Time: 625
Time: 640
Time: 641
Time: 609
Time: 625
Time: 625
Time: 610
Time: 609
Time: 625
Time: 625
Time: 422
Time: 625
Time: 594
Time: 609
Time: 625
Time: 594
Time: 594
Time: 625

问题出在哪里?

推荐答案


我要求每秒发送n条消息,我认为等待/通知不合适,对吗?

I have a requirement to send n messages per second, I think wait/notify don't fit, correct?

如果您有严格的时间要求,那么您将需要使用实时Java 实施。主流SE和ME Java实现不适合硬实时应用。

If you have a hard timing requirement, then you are going to need to use a real-time Java implementation. Mainstream SE and ME Java implementations are not suitable for hard realtime applications.

您可以使用各种技巧来满足大多数时间的要求......但是如果您的应用程序/系统过载,您可能会开始错过所需的消息率。

There are various tricks you can use to meet such requirements "most of the time" ... but if your application / system gets overloaded you are liable start to missing the required message rate.

真正的问题不在于计时器的准确性,而是非事实-realtime调度程序不会(也不能)保证在计时器到期后安排线程运行。

Th real problem is not the accuracy of the timers, but the fact that a non-realtime scheduler won't (and can't) guarantee to schedule the thread to run as soon as the timer expires.

这篇关于Thread.sleep等待超过预期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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