java之thread.yield

yield,看到很多文章把yield理解为暂停,其实是不准确的,翻译过来用让步更为准确一些。简单描述下其作用:

使调用yield的正在执行的线程让出cpu,让同等优先权的其他线程包括自身重新进行分配调度

概念性的东西或许有些难理解,打个比方,有一个题库,里面有很多数学题目,学生来抽取题库中的题来解答,其中题库相当所有线程,题目相当于单个线程,学生相当于cpu。那么某一次抽取到题目A,开始解答,解到一半,吧唧,调用了个yield,好的,这个时候学生会把未做完的题目A放回题库,然后重新选取一个题目进行解答,那么下一次选取到哪个题目,仍然是学生自己决定,可能选到题目B、C、D...但是,也可能仍然选到题目A,这就是yield的作用。

demo如下

public class MyThreadYield implements Runnable{


    @Override
    public void run() {
        for (int i = 10; i < 20; i++) {
            System.out.println(Thread.currentThread().getName() + ":priority-" + Thread.currentThread().getPriority() + "-------" + i);

            if (i == 15) {
                Thread.yield();
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new MyThreadYield());
        thread.setName("first");

        Thread thread1 = new Thread(new MyThreadYield());
        thread1.setName("second");

        thread.start();
        thread1.start();

    }

}

在java doc中我们可以看到官方的解释,yield更多的是作为调试或测试时候使用(也就是疯狂重分配,提高切换概率,模拟并发)

/**
     * 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();

评论

暂无评论