Thread.sleep(long) 的效果如何?

发布于 2024-08-28 04:55:38 字数 67 浏览 5 评论 0原文

假设我想“暂停”一个线程,以便其他线程可以更有效地运行。在阻塞变得毫无意义(或几乎毫无意义)之前,最短的睡眠时间是多少?

Let's say I want to "pause" a thread so that other threads can run more efficiently. What is the minimum sleeping period before blocking becomes pointless (or almost pointless)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

最近可好 2024-09-04 04:55:38

我希望任何数量的睡眠至少在功能上等同于调用 yield() ,因此永远不会有“毫无意义”的点。肯定有一个点,小值本质上是无法区分的,因为等待操作系统返回线程的开销比小的睡眠时间要长。这可能发生在 5-10 范围内的某个地方,但当然这将是特定于操作系统的。

I would expect that any amount of sleeping would at least be the functional equivalent of calling yield() so there is never a point where it is "pointless." There is a definitely a point where a small values are essentially indistinguishable because the overhead of waiting for the Operating System to get back around to your thread is longer than a small sleep time. That probably occurs somewhere in the 5-10 range, but of course it will be OS specific.

千紇 2024-09-04 04:55:38

这很难一概而论,并且会因您的具体问题而异。但是,我不会自己使用睡眠来管理线程。您可以将线程放入Executor 中并让它管理它们。您还可以使用 PriorityQueue 来对任务进行排序。

That's difficult to generalize and would vary by your specific problem. But, I wouldn't use sleep yourself to manage the threads. You can put the threads into an Executor and let it manage them. You can also use a PriorityQueue to order your tasks.

风情万种。 2024-09-04 04:55:38

IIRC甚至Thread.sleep(0)都会导致线程让出,允许具有相同或更高优先级的其他线程运行。

这取决于线程优先级...我的理解是 Thread.sleep 有效地产生线程,并将其优先级设置为睡眠期间的最低优先级。

正如其他人提到的,您可能不应该使用它来手动安排线程。但是,如果您有共享互斥体,您可能希望释放它们,然后执行 Thread.sleep 来帮助解决线程锁定情况,这很有用。

IIRC even Thread.sleep(0) will cause the thread to yield, allowing other threads with the same or higher priority to run.

It depends on thread priority... My understanding is that Thread.sleep effectively yields the thread, and sets it's priority to the lowest for the duration of the sleep.

As others have mentioned, you probably shouldn't be using this to schedule your threads manually. It is useful however, if you have shared mutexes you may want to release them and then do a Thread.sleep to help resolve a threadlock situation.

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