线程睡眠和精确计时 [英] Thread sleep and precise timing

查看:177
本文介绍了线程睡眠和精确计时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个代码,我希望在时机上有一定的精确度。我用机器人做了一些动作,然后我用 Thread.sleep(some_time)来实现 some_time 行动。但是我没有得到最好的结果,因为当我搜索它时, sleep 是不准确的。实现这一目标的最佳方法是什么?我的意思是用其他方法模拟 Thread.sleep

I am making a code where I want definite precision in my timing. I use a robot to make some actions, then I use Thread.sleep(some_time) for some_time to be elapsed between the actions. But I don't get best results because as I search it, sleep is not accurate. What would be the best way to accomplish this? I mean simulate Thread.sleep with other methods.

推荐答案

时间安排现代操作系统永远不会精确,除非您使用为此明确设计的语言/框架。但是,在大多数操作系统中,您可以使用合理的不确定性。但合理取决于你要解决的问题。

Timing in modern OSes is never precise, unless you use a language/framework that was explicitly designed for this. You can however work with a reasonable uncertainty in most operation systems. But "reasonable" depends on the problem you are trying to solve.

在Java中,Thread.sleep是一个非常基本的实现,在我看来过于夸张。 Java提供这些基本的线程工具并不是因为它们是最好的解决方案,而是因为它们是基本的工具。 Java还提供了许多其他更复杂的工具,可以更好地满足您的需求。

In Java Thread.sleep is a very basic implementation that is way too overused in my opinion. Java offers these basic threading tools not because they are the best solution, but because they are basic tools. Java as well offers many other, more sophisticated tools, that might suit your needs much better.

例如,如果您想要精确计时,您可以使用< a href =http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html =noreferrer> ScheduledExecutorService ,它使用操作系统调度服务提供至少毫秒的精度,甚至通常为纳秒。虽然它不是精确到纳秒(尽管提供),但它通常比Thread.sleep准确得多。但是在严重超载的系统上,两者都不准确。如果这足以解决您的问题,那么您应该采用这种方法。否则,您需要一个不同的语言/执行环境。

In example if you want "precise" timing, you can instead use a ScheduledExecutorService, which uses the OS scheduling service to offer a precision of at least milliseconds, and often even nanoseconds. Although it is not exact to the nanosecond (despite the offer), it will usually be much more accurate than Thread.sleep. But both will not be accurate on a heavily overloaded system. If this is sufficient for your problem, then you should go with this. Otherwise you need a different language/execution environment.

这篇关于线程睡眠和精确计时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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