`
hz_chenwenbiao
  • 浏览: 996190 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

sleep()和yield()的区别(转)

阅读更多

1) sleep()使当前线程进入停滞状态,所以执行sleep()的线程在指定的时间内肯定不会执行

yield()只是使当前线程重新回到可执行状态(yield只是屈服一个同级的对手,也可以说是让一下它们),所以执行yield()的线程有可能在进入到可执行状态后马上又被执行。

 

2) sleep()可使优先级低的线程得到执行的机会,当然也可以让同优先级和高优先级的线程有执行的机会;

yield()只能使同优先级的线程有执行的机会

 

public class ThreadTest implements Runnable{

public void run(){

for(int k=0;k<10;k++){

if(k == 5 && Thread.currentThread().getName().equals("t1")){

Thread.yield();

}

System.out.println(Thread.currentThread().getName()+ " : " + k);

}

}

public static void main(String[] args) {

Runnable r = new ThreadTest();

Thread t1 = new Thread(r,"t1");

Thread t2 = new Thread(r,"t2");

t1.setPriority(Thread.MAX_PRIORITY);

t2.setPriority(Thread.MIN_PRIORITY);

t1.start();

t2.start();

}

}

输出结果:

t1 : 0

t1 : 1

t1 : 2

t1 : 3

t1 : 4

t1 : 5

t1 : 6

t1 : 7

t1 : 8

t1 : 9

t2 : 0

t2 : 1

t2 : 2

t2 : 3

t2 : 4

t2 : 5

t2 : 6

t2 : 7

t2 : 8

t2 : 9

多次运行这个程序,输出也是一样。这说明:

yield()方法不会使不同优先级的线程有执行的机会。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics