线程休眠:我们希望人为地控制线程,使得正在执行的线程暂停,将CPU让给别的线程,我们可以使用静态方法sleep(long millis),该方法可以让当前正在执行的线程暂停一段时间,进入休眠等待状态。
线程让步:线程让步可以通过yield() 方法来实现,该方法和sleep()有点相似,都可以让当前正在运行的线程暂停,区别在于yield()方法不会阻塞该线程,他只是将线程转换成就绪状态,让系统调度器重新调度一次。当某个线程调用yield()方法之后,只有与当前线程优先级相同或者更高的线程才能获得执行的机会。
线程休眠简单实例:
public class ThreadSleep { public static void main(String[] args) { new Thread(new SleepThread()).start(); for(int i=1;i<=10;i++) { if(i == 5) { System.out.println("mainThread start sleep!"); try { Thread.sleep(20000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("mainThread is inputting:"+i); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } class SleepThread implements Runnable { @Override public void run() { // TODO Auto-generated method stub for (int i = 0; i < 10; i++) { if (i == 3) { System.out.println("deputyThread start sleep!"); try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("deputyThread is inputting:"+i); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
线程让步简单实例:
public class ThreadYield { public static void main(String[] args) { new Thread(new YieldThread(),"Thread A").start(); new Thread(new YieldThread(),"Thread B").start(); new Thread(new YieldThread(),"Thread C").start(); new Thread(new YieldThread(),"Thread E").start(); new Thread(new YieldThread(),"Thread F").start(); new Thread(new YieldThread(),"Thread G").start(); new Thread(new YieldThread(),"Thread H").start(); } } class YieldThread implements Runnable{ @Override public void run() { // TODO Auto-generated method stub for(int i = 0;i <=10;i++) { if(i == 4) { System.out.println(Thread.currentThread().getName()+" that is inputting "+i+" has yielded!"); continue; } System.out.println(Thread.currentThread().getName()+" is inputting :"+i); } } }