Java 系统时钟独立调度/暂停
我需要一种以独立于系统时钟的方式暂停/睡眠线程的方法。这意味着,如果我希望一个线程在 dT 毫秒内变弱,那么如果系统时间在此期间发生显着变化,它也必须这样做。我对以毫秒为单位的准确性不太感兴趣,更原则上它会起作用。
TimerTasks 不是一个选项,因为它们工作在绝对时间上。
I need a way to pause/sleep a thread in a system clock independent way. Meaning, that if I want a Thread to weak up in dT msecs it must do so also if the system time changes significantly during this time. I am not so much interested in accuracy in msecs and more in principle that it will work.
TimerTasks are not an option since they work on absolute time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Thread.sleep(millis );
Thread.sleep(millis);
棘手......很难知道系统时钟是否用于任何给定的策略。但是,您避免使用时钟是因为时间可能会在线程暂停期间发生更改,但 System.nanoTime() 与当前时间无关,因为它纯粹是自 JVM 启动以来的纳秒数。因此,如果暂停策略使用纳秒,人们可能会假设暂停周期将通过系统时钟时间变化保持准确性。也许 Thread.join(0, nanos) 在循环中调用:
我没有使用系统时钟更改进行测试,但它似乎在 0.004% 的偏差内运行。
Tricky.... it's tough to know if the system clock is even being used for any given strategy. However, your avoidance of the clock is because the time might be changed during the thread pause, but System.nanoTime() is independent of the current time since it is purely the number of nanoseconds since the JVM started. Accordingly, if the pause strategy uses nanos, one might assume that the pause periods will retain accuracy through system clock time changes. Perhaps Thread.join(0, nanos) called in a loop:
I did not test with system clock changes, but it appears to run within a .004% deviation.
我不确定我是否正确理解你的问题。如果您需要任务调度程序,Quartz 非常不错。如果您实际上想将任意线程暂停 x 时间,那么这可能会更加棘手。
I'm not sure if I understand your question correctly. If you need a task scheduler, Quartz is pretty good. If you actually want to pause an arbitrary thread for x amount of time than that can be a little more tricky.