这是Java中的一种线程让步方法,让Java中的线程从执行状态变成就绪状态,然后处理器再从就绪队列中挑选线程进行执行(优先级大的,被挑选的概率较大),这种转换也不确定,让或者不让都是取决与处理器,线程可能继续占有处理器。
**
* 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
* {@link java.util.concurrent.locks} package.
*/
//暗示调度器让当前线程让出占用的处理器,但是让或者是不让,都是调度器自己决定的,有可能调用此方法过后,线程依然占用处理器
public static native void yield();
看《Java并发编程艺术》这本书,里面有用到Thread.yield方法,来测试Java线程优先级,代码如下:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class Priority {
private static volatile boolean notStart=true;
private static volatile boolean notEnd=true;
public static void main(String[] argvs) throws Exception{
List jobs=new ArrayList();
for(int i=0;i<10;i++){
int priority=i<5?Thread.MIN_PRIORITY:Thread.MAX_PRIORITY;
Job job=new Job(priority);
jobs.add(job);
Thread thread=new Thread(job,"Thread:"+i);
thread.setPriority(priority);
thread.start();
}
notStart=false;
TimeUnit.SECONDS.sleep(10);
notEnd=false;
for(Job job:jobs){
System.out.println("Job Priority:"+job.priority+", Count: "+job.jobCount);
}
}
static class Job implements Runnable{
private int priority;
private long jobCount;
public Job(int priority){
this.priority=priority;
}
@Override
public void run() {
while(notStart){
Thread.yield();
}
while(notEnd){
Thread.yield();
jobCount++;
}
}
}
}
跑出结果如下:
Job Priority:1, Count: 6087836
Job Priority:1, Count: 6573345
Job Priority:1, Count: 6024024
Job Priority:1, Count: 6606573
Job Priority:1, Count: 6901572
Job Priority:10, Count: 6118724
Job Priority:10, Count: 5968747
Job Priority:10, Count: 5939391
Job Priority:10, Count: 6206129
Job Priority:10, Count: 6187854
发现即使线程优先级为1和为10的线程,最后获取CPU的次数是差不多的,没有明显差距,线程优先级没有生效。程序的正确性不能依赖于线程的优先级。