V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
gengzi
V2EX  ›  Java

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

  •  
  •   gengzi · 2021-09-18 16:06:21 +08:00 · 1541 次点击
    这是一个创建于 922 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

    4 条回复    2021-09-22 14:00:46 +08:00
    kkkkkrua
        1
    kkkkkrua  
       2021-09-18 17:25:45 +08:00
    意思就是 sleep 的优雅版
    carrotrollroll
        2
    carrotrollroll  
       2021-09-19 13:51:35 +08:00
    这不是每次循环都出让一次嘛?
    xxxrubyxxx
        3
    xxxrubyxxx  
       2021-09-19 19:44:31 +08:00
    让出线程拿到的时间片,让其他线程去竞争,Thread.sleep()会让线程阻塞在哪里,浪费 cpu 资源
    huang119412
        4
    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
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5824 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 01:55 · PVG 09:55 · LAX 18:55 · JFK 21:55
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.