多线程_yield()和sleep()方法比较
多线程示例展示:
RabbitThread.java线程:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package thread; 2 3 /** 4 * 兔子的线程 5 * @author superdrew 6 */ 7 public class RabbitRunnable implements Runnable{ 8 9 public void run() { 10 while(true){ 11 12 System.out.println("兔子领先了....加油!!!!"+ 13 Thread.currentThread().getName()+" "+Thread.currentThread().getPriority()); 14 15 //Thread.yield(); 16 } 17 } 18 19 }
TortoiseThread.java线程:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package thread; 2 3 public class TortoiseThread extends Thread{ 4 //线程属性名字: name 5 private String name; 6 //无参数构造方法 7 public TortoiseThread(){} 8 //有参数构造方法 9 public TortoiseThread(String name){ 10 super(name); 11 } 12 13 public void run() { 14 while(true){ 15 System.out.println("乌龟领先了。。。加油。。。。。。"+getName() +" "+getPriority()); 16 Thread.yield(); 17 } 18 } 19 }
TestThread线程:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package thread; 2 /** 3 * 功能:龟兔赛跑 4 * 使用线程 5 * yield(); 6 * @author superdrew 7 * 作用:暂停当前正在执行的线程对象,并执行其他线程 8 * 调用yield()当前线程进入就绪状态,可以和其它的就绪状态的线程争取cpu 9 * 如果其它的线程优先级别高,那么其它的线程获取cpu的机率就大一些 10 * 11 * yield()和sleep()区别 12 * 1.sleep()是暂停进入阻塞状态,只有睡眠时间到了 进入就绪状态 13 * yield()是直接进入就绪状态,有可能刚进入就绪状态就获取到cpu又执行 14 * 2.yield()无异常 sleep()有 15 * 16 * 17 */ 18 public class TestThread1 { 19 public static void main(String[] args) { 20 RabbitRunnable rr = new RabbitRunnable(); 21 Thread tr = new Thread(rr); 22 tr.setName("兔子线程"); 23 tr.start(); 24 25 TortoiseThread tt = new TortoiseThread("乌龟线程"); 26 tt.start(); 27 } 28 }