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.