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