Java编程语言中sleep()和yield()的区别


  本文标签:Java编程语言

Java编程语言在使用中有很多需要我们学习的,下面我们就来看看sleep()和yield()的区别之间的区别,希望大家在详细学习中有所收获  。只有在不断的学习才能更好的使用  。

1) sleep()使当前线程进入停滞状态,所以执行sleep()的线程在指定的时间内肯定不会执行;yield()只是使当前线程重新回到可执行状态,所以执行yield()的线程有可能在进入到可执行状态后马上又被执行  。

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

  1. class TestThreadMethod extends Thread{  
  2. public static int shareVar = 0;  
  3. public TestThreadMethod(String name){  
  4. super(name);  
  5. }  
  6. public void run(){  
  7. for(int i=0; i<4; i++){  
  8. System.out.print(Thread.currentThread().getName());  
  9. System.out.println(" : " + i);  
  10. //Thread.yield(); (1)  
  11. /* (2) */  
  12. try{  
  13. Thread.sleep(3000);  
  14. }  
  15. catch(InterruptedException e){  
  16. System.out.println("Interrupted");  
  17. }}}  
  18. }  
  19. public class TestThread{  
  20. public static void main(String[] args){  
  21. TestThreadMethod t1 = new TestThreadMethod("t1");  
  22. TestThreadMethod t2 = new TestThreadMethod("t2");  
  23. t1.setPriority(Thread.MAX_PRIORITY);  
  24. t2.setPriority(Thread.MIN_PRIORITY);  
  25. t1.start();  
  26. t2.start();  
  27. }  

运行结果为:

  1. t1 : 0  
  2. t1 : 1  
  3. t2 : 0  
  4. t1 : 2  
  5. t2 : 1  
  6. t1 : 3  
  7. t2 : 2  
  8. t2 : 3 

由结果可见,通过sleep()可使优先级较低的线程有执行的机会  。注释掉代码(2),并去掉代码(1)的注释,结果为:

  1. t1 : 0  
  2. t1 : 1  
  3. t1 : 2  
  4. t1 : 3  
  5. t2 : 0  
  6. t2 : 1  
  7. t2 : 2  
  8. t2 : 3 

可见,调用yield(),不同优先级的线程永远不会得到执行机会  。

以上就是对Java编程语言的相关介绍,希望大家有所帮助  。