理论上,yield意味着放手,放弃,投降。一个调用yield()方法的线程告诉虚拟机它乐意让其他线程占用自己的位置。这表明该线程没有在做一些紧急的事情。注意,这仅是一个暗示,并不能保证不会产生任何影响。
在Thread.java中yield()定义如下:
1
2
3
4
5
6
7
|
/**
* 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-utilize a CPU.
* Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect.
*/
public
static
native
void
yield();
|
让我们列举一下关于以上定义重要的几点:
- Yield是一个静态的原生(native)方法
- Yield告诉当前正在执行的线程把运行机会交给线程池中拥有相同优先级的线程。
- Yield不能保证使得当前正在运行的线程迅速转换到可运行的状态
- 它仅能使一个线程从运行状态转到可运行状态,而不是等待或阻塞状态
package java_thread.learn01.c002;
public class yieldTest extends Thread{
@Override
public void run(){
long btime = System.currentTimeMillis();
int count = 0;
for(int i = 0;i<50000000;i++){
Thread.yield();
count = count + (i + 1);
}
long etime = System.currentTimeMillis();
System.out.println("用时:" +(etime -btime) + "毫秒");
}
}
package java_thread.learn01.c002;
public class yieldRun {
public static void main(String[] args) {
yieldTest yt = new yieldTest();
yt.start();
}
}
上面代码,如果注释Thread.yield();,则时间20毫秒左右,如果不注释,则5030毫秒左右,自己测试看看。