Java中Thread.yield()和Thread.sleep(0)有什么区别?

发布于 2024-10-14 21:28:53 字数 526 浏览 6 评论 0原文

可能的重复:
Thread.sleep(0) 和 Thread.yield() 语句是否等效?

根据我的理解,Thread.yield() 和 Thread.sleep(0) 都应该让 CPU 通过某种调度算法重新判断要运行哪个线程。

区别在于:

  1. Thread.yield() 是给其他线程执行机会,而 Thread.sleep(0) 不会,它只是告诉 CPU 你应该重新安排执行线程,包括当前线程本身.

  2. Thread.yield() 只是一个建议,这意味着它可能根本不被接受,但是 Thread.sleep(0) 会强制进行重新排列。

以上两个结论对吗?

Possible Duplicate:
Are Thread.sleep(0) and Thread.yield() statements equivalent?

In my understanding, both Thread.yield() and Thread.sleep(0) should make the CPU rejudge which thread to run by some scheduling algorithm.

The difference is:

  1. Thread.yield() is to give the executive chance to other threads, but Thread.sleep(0) will not, it'll just tell CPU that you should rearrange the executive threads including the current thread itself.

  2. Thread.yield() is just an advice which means it may not be accepted at all, but Thread.sleep(0) will do the rearrangement forcedly.

Are the two above conclusions right?

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

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

发布评论

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

评论(2

逆蝶 2024-10-21 21:28:53

Thread.Sleep() 的开销稍大一些,因为它创建的系统包含某种可以唤醒进程的计时器。 (基本上取决于实施)
最重要的是,它最终会调用 Yield()

Thread.Yield() 只会放弃线程的回合,并在下一轮中获得它。

Thread.Sleep(0) 可能有一个优化,只调用yield。 (再次,实施)

Thread.Sleep() has a slightly larger overhead because it creates a system that includes some kind of timer that will wake the process. (Depends on implementation basically)
Bottom line it will call a Yield() in the end.

Thread.Yield() Will just give-up the thread's turn, and gain it in the next round.

Thread.Sleep(0) might have an optimization to just call yield. (Again, implementation)

恬淡成诗 2024-10-21 21:28:53

Thread.sleep() 只会暂停线程,不会放弃控制权。
Thread.yield() 将暂停线程并允许其他线程运行。如果没有线程需要,原始线程将立即恢复。

Thread.sleep() will just pause the thread and not give away control.
Thread.yield() will pause the thread and allow other threads to run. If no threads need to, the original thread will resume immediately.

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