看 Ribbon 轮询的负载策略源码中,循环获取可用服务,使用了 Thread.yield()有什么用意?

2021-09-18 16:06:21 +08:00
 gengzi

while (server == null && count++ < 10) { // 省略。。 if (server == null) { /* Transient. */ Thread.yield(); continue; } // 省略。。 }

看代码应该是 9 年期,难道只是出让一次机会给别的线程执行?

1579 次点击
所在节点    Java
4 条回复
kkkkkrua
2021-09-18 17:25:45 +08:00
意思就是 sleep 的优雅版
carrotrollroll
2021-09-19 13:51:35 +08:00
这不是每次循环都出让一次嘛?
xxxrubyxxx
2021-09-19 19:44:31 +08:00
让出线程拿到的时间片,让其他线程去竞争,Thread.sleep()会让线程阻塞在哪里,浪费 cpu 资源
huang119412
2021-09-22 14:00:46 +08:00
看注释:A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.
实际上这个可以极大增加 CPU 利用率,Disruptor 高性能就是靠 CAS + yield

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/802797

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX