yield方法的作用是放弃当前的CPU资源,将它让给其它的任务去占用CPU执行时间。但放弃的时间不确定,有可能刚刚放弃,马上又获得CPU时间片。今天我们通过实例来学习一下yield()方法的使用。最是那一低头的温柔 像一朵水莲花不胜凉风的娇羞。

yield方法的简单实例

一、yield方法的简单使用

public class YieldThread extends Thread {
YieldThread(String string) {
super(string);
} @Override
public void run() {
for (int i = 0; i < 10; i ++) {
System.out.println(getName() + ", " + i);
if (i % 2 == 0) {
Thread.yield();
}
}
}
}

测试的主体类如下:

public class YieldThreadTest {
public static void main(String[] args) {
YieldThread thread1 = new YieldThread("thread 1");
YieldThread thread2 = new YieldThread("thread 2"); thread1.start();
thread2.start();
}
}

一次的运行结果如下:

thread ,
thread ,
thread ,
thread ,
thread ,
thread ,
thread ,
thread ,
thread ,
thread ,
thread ,
thread ,
thread ,
thread ,
thread ,
thread ,
thread ,
thread ,
thread ,
thread ,

从上述的结果可以看到每次i为偶数的时候,都会切换了线程。但是这种现象不能得到保证,只是一种趋势。yield的真正用途是:使当前线程从执行态变为可执行态,也就是就绪态吧。cpu会从众多的可执行态里选择,也就是说,当前也就是刚刚的那个线程还是有可能会被再次执行到的,并不是说一定会执行其他线程而该线程在下一次不会执行到了。官方文档的解释:

  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.
  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.
  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 java.util.concurrent.locks package.

友情链接

最新文章

  1. 基于netty-socketio的web推送服务
  2. SQL Server 2008 master 数据库损坏解决总结
  3. 20145224&amp;20145238 《信息安全系统设计基础》 第四次实验
  4. 【 D3.js 入门系列 --- 3 】 做一个简单的图表!
  5. 【python】获取高德地图省市区县列表
  6. Linux/Unix mac 命令笔记
  7. mac 设置 ll 等alias 并永久生效
  8. FXBlurView用法
  9. zabbix流量汇聚
  10. android Graphics(三):区域(Range)
  11. [Manacher]【学习笔记】
  12. PCIE4.0 简单介绍
  13. 谷歌浏览器中安装Axure扩展程序
  14. poj3468 线段树的懒惰标记
  15. (二)Makefile——自动编译、清理、安装软件
  16. PJ初赛复习日记
  17. boost 线程安全队列
  18. 流水的新技术,铁打的Linux
  19. .Net2.0部署在IIS8.5上的问题
  20. 使用windows server2012时FileZilla客户端连接时报150 Opening data channel for directory listing of &quot;/&quot; 响应:425 Can&#39;t open data connection

热门文章

  1. 【WPF】ListBox无法滚动
  2. SSI——服务器端嵌入
  3. mysql 创建新用户并添加权限
  4. kettle中执行sql语句
  5. hadoop错误之ClassNotFoundException(下)
  6. font-face自定义字体
  7. 使用 jQuery UI 和 jQuery 插件构建更好的 Web 应用程序
  8. 关于Cocos2d-x程序运行时候提示关闭程序的框框的解决方法
  9. JavaScript 中,num = num || 1 这种写法有哪些优缺点?
  10. C++编程 - tuple、any容器