java之thread.yield

发布时间:2019-11-17 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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();

脚本宝典总结

以上是脚本宝典为你收集整理的java之thread.yield全部内容,希望文章能够帮你解决java之thread.yield所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。