gengzi
V2EX  ›  Java

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

  •  
  •   gengzi · Sep 18, 2021 · 2703 views
    This topic created in 1727 days ago, the information mentioned may be changed or developed.

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

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

    4 replies    2021-09-22 14:00:46 +08:00
    kkkkkrua
        1
    kkkkkrua  
       Sep 18, 2021
    意思就是 sleep 的优雅版
    carrotrollroll
        2
    carrotrollroll  
       Sep 19, 2021
    这不是每次循环都出让一次嘛?
    xxxrubyxxx
        3
    xxxrubyxxx  
       Sep 19, 2021
    让出线程拿到的时间片,让其他线程去竞争,Thread.sleep()会让线程阻塞在哪里,浪费 cpu 资源
    huang119412
        4
    huang119412  
       Sep 22, 2021
    看注释: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
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3590 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 10:31 · PVG 18:31 · LAX 03:31 · JFK 06:31
    ♥ Do have faith in what you're doing.