yield()函数的作用是让步,它让当前线程由运行状态进入就绪状态,而不是像wait()一样进入阻塞状态。因此,并不能保证在当前线程调用yield()之后,其他具有相同优先级的线程一定能获得执行权,也有可能是当前线程又重新进入了运行状态。
示例代码:
- class ThreadA extends Thread{
- public ThreadA(String name){
- super(name);
- }
- public synchronized void run(){
- for(int i=0; i <10; i++){
- System.out.printf("%s [%d]:%d\n", this.getName(), this.getPriority(), i);
- // i整除4时,调用yield
- if (i%4 == 0)
- Thread.yield();
- }
- }
- }
- public class NotifyAllTest {
- public static void main(String[] args) {
- ThreadA t1 = new ThreadA("t1");
- ThreadA t2 = new ThreadA("t2");
- t1.start();
- t2.start();
- }
- }
运行结果:
t2 [5]:0
t1 [5]:0
t2 [5]:1
t2 [5]:2
t2 [5]:3
t2 [5]:4
t1 [5]:1
t1 [5]:2
t1 [5]:3
t1 [5]:4
t2 [5]:5
t2 [5]:6
t2 [5]:7
t2 [5]:8
t2 [5]:9
t1 [5]:5
t1 [5]:6
t1 [5]:7
t1 [5]:8
t1 [5]:9
yield()虽然可以让线程由运行状态进入到就绪状态,但最后谁获取CPU的执行权限是不一定的。