多线程 - yield()能立马让线程让出CPU时间片么?

答案:不能

线程之间的关系,是“协同式”的,不是“抢占式”的。

yield不会强制让渡CPU, interrupt也不会强制停止线程。

根据源码注释:

  • 调用yield,只是想处理器processor暗示:“当前线程愿意让渡yield时间片”。但是处理器可以自由的忽略这个暗示。
  • 这就说明了:线程之间的关系,是“协同式”的,不是“抢占式”的
  • yield方法对于debugging或者testing的帮助很大,可以帮助减少由于竞争条件造成的bug
/**
     * 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.
     *
     * <p> Yield is a heuristic attempt to improve relative progression
     * between threads that would otherwise over-utilise a CPU. Its use
     * should be combined with detailed profiling and benchmarking to
     * ensure that it actually has the desired effect.
     *
     * <p> It is rarely appropriate to use this method. It may be useful
     * for debugging or testing purposes, where it may help to reproduce
     * bugs due to race conditions. It may also be useful when designing
     * concurrency control constructs such as the ones in the
     * {@link java.util.concurrent.locks} package.
     */
    public static native void yield();

 

posted on 2021-10-13 14:56  frank_cui  阅读(326)  评论(0编辑  收藏  举报

导航

levels of contents