Java 系统时钟独立调度/暂停

发布于 2024-10-08 18:16:53 字数 155 浏览 4 评论 0原文

我需要一种以独立于系统时钟的方式暂停/睡眠线程的方法。这意味着,如果我希望一个线程在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

Oo萌小芽oO 2024-10-15 18:16:53

棘手......很难知道系统时钟是否用于任何给定的策略。但是,您避免使用时钟是因为时间可能会在线程暂停期间发生更改,但 System.nanoTime() 与当前时间无关,因为它纯粹是自 JVM 启动以来的纳秒数。因此,如果暂停策略使用纳秒,人们可能会假设暂停周期将通过系统时钟时间变化保持准确性。也许 Thread.join(0, nanos) 在循环中调用:

public static void pause(long ms) throws InterruptedException {
   long final ZERO = 0L;
   int final MAX_NANOS = 999999;
   for(int i = 0; i < ms+1; i++) {
      Thread.currentThread().join(ZERO, MAX_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:

public static void pause(long ms) throws InterruptedException {
   long final ZERO = 0L;
   int final MAX_NANOS = 999999;
   for(int i = 0; i < ms+1; i++) {
      Thread.currentThread().join(ZERO, MAX_NANOS);
   }
}

I did not test with system clock changes, but it appears to run within a .004% deviation.

以为你会在 2024-10-15 18:16:53

我不确定我是否正确理解你的问题。如果您需要任务调度程序,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文