Thread中sleep()与yield()的区别

来源:互联网 发布:dijkstra算法求解过程 编辑:程序博客网 时间:2024/06/06 20:14

package com.mxx.demo;

/*

 * sleep:会强制让当前线程进入等待,即当前线程的状态为:等待、阻塞

 * yield:会先去判断是否有和当前线程相同优先级的线程,如果没有,则自己继续执行,如果

 *      有,则将CPU资源让给它,然后进入到就绪状态。

 *

 */

class MyThread1extends Thread

{

   public void run(){

      for(int i = 1; i <= 10; i++)

      {

         System.out.println(getName() +" ..." + i);

         Thread.yield();

      }

   }

}

publicclass Demo2

{

   public staticvoid main(String[] args)

   {

      MyThread1 th1 =new MyThread1();

      MyThread1 th2 =new MyThread1();

 

      th1.start();

      th2.start();

   }

}
0 0
原创粉丝点击