Thread.yield()简介

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_15037231/article/details/85765322

Thread.yield()方法

(1)方法源码注释:

/**
 * 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.
 */

大致意思:yield()方法会通知线程调度器放弃对处理器的占用,但调度器可以忽视这个通知。yield()方法主要是为了保障线程间调度的连续性,防止某个线程一直长时间占用cpu资源。但是他的使用应该基于详细的分析和测试。这个方法一般不推荐使用,它主要用于debug和测试程序,用来减少bug以及对于并发程序结构的设计。

(2)方法理解:

Thread.yield()方法很多人翻译成线程让步,就是说当一个线程使用了这个方法之后,它就会把自己CPU执行的时间让掉,使当前线程从执行状态(运行状态)变为可执行态(就绪状态),自己或者其它的线程运行。cpu调度器会从众多的可执行态里选择,也就是说,当前也就是刚刚的那个线程还是有可能会被再次执行到的,并不是说一定会执行其他线程而该线程在下一次中不会执行到了。

打个比方:现在有很多人在排队上厕所,好不容易轮到这个人上厕所了,突然这个人说:“我要和大家来个竞赛,看谁先抢到厕所!”,然后所有的人在同一起跑线冲向厕所,有可能是别人抢到了,也有可能他自己有抢到了。我们还知道线程有个优先级的问题,那么手里有优先权的这些人就一定能抢到厕所的位置吗? 不一定的,他们只是概率上大些,也有可能没特权的抢到了。

例子:

package com.yield;  
  
public class YieldTest extends Thread {  
  
    public YieldTest(String name) {  
        super(name);  
    }  
  
    @Override  
    public void run() {  
        for (int i = 1; i <= 50; i++) {  
            System.out.println("" + this.getName() + "-----" + i);  
            // 当i为30时,该线程就会把CPU时间让掉,让其他或者自己的线程执行(也就是谁先抢到谁执行)  
            if (i == 30) {  
                this.yield();  
            }  
        }  
    }  
  
    public static void main(String[] args) {  
        YieldTest yt1 = new YieldTest("张三");  
        YieldTest yt2 = new YieldTest("李四");  
        yt1.start();  
        yt2.start();  
    }  
}  


运行结果:

第一种情况:李四(线程)当执行到30时会CPU时间让掉,这时张三(线程)抢到CPU时间并执行。

第二种情况:李四(线程)当执行到30时会CPU时间让掉,这时李四(线程)抢到CPU时间并执行。

猜你喜欢

转载自blog.csdn.net/qq_15037231/article/details/85765322