线程休眠的目的是使线程让出CPU的最简单的做法之一,线程休眠时候,会将CPU资源交给其他线程,以便能轮换执行,当休眠一定时间后,线程会苏醒,进入准备状态等待执行。线程休眠的方法是Thread.sleep(long millis) 和Thread.sleep(long millis, int nanos) ,均为静态方法,那调用sleep休眠的哪个线程呢?简单说,哪个线程调用sleep,就休眠哪个线程。
继承Thread和实现Runnable,具体实现代码如下:
/** * @author www.yoodb.com */ public class Test { public static void main(String[] args) { Thread t1 = new MyThread(); Thread t2 = new Thread(new MyRunnable()); t1.start(); t2.start(); } }
public class MyThread extends Thread { public void run() { for (int i = 0; i < 6; i++) { System.out.println("线程1第" + i + "次执行!"); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } } }
public class MyRunnable implements Runnable { public void run() { for (int i = 0; i < 6; i++) { System.out.println("线程2第" + i + "次执行!"); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } } }
运行结果,如下:
线程2第0次执行! 线程1第0次执行! 线程1第1次执行! 线程2第1次执行! 线程1第2次执行! 线程2第2次执行! 线程2第3次执行! 线程1第3次执行! 线程2第4次执行! 线程2第4次执行! 线程1第5次执行! 线程2第5次执行!