sleep是Thread类的静态方法。sleep的作用是让线程休眠制定的时间,在时间到达时恢复,也就是说sleep将在接到时间到达事件事恢复线程执行,例如:
new Thread() { @Override public void run() { try { System.out .println("子线程休眠——————————————————————————————————————"); Thread.sleep(5000); System.out .println("子线程继续——————————————————————————————————————"); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); int i = 0; while (true) { try { System.out.println("主线程休眠" + i++); Thread.sleep(1000); System.out.println(new Date().getSeconds()); System.out.println("主线程继续"); } catch (InterruptedException e) { e.printStackTrace(); } }wait是Object的方法,也就是说可以对任意一个对象调用wait方法,调用wait方法将会将调用者的线程挂起,直到其他线程调用同一个对象的notify方法才会重新激活调用者(或wait(time),但这种用法很少),例如:
new Thread() { @Override public void run() { try { synchronized (Obj.class) { System.out .println("子线程休眠——————————————————————————————————————"); Obj.class.wait(); System.out .println("子线程继续——————————————————————————————————————"); } } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); int i = 0; synchronized (Obj.class) { while (i != 5) { i++; System.out.println(new Date().getSeconds()); } System.out.println("唤醒"); Obj.class.notify(); }控制台输出:
子线程休眠—————————————————————————————————————— 51 52 53 54 54 唤醒 子线程继续——————————————————————————————————————
原文地址:http://blog.csdn.net/tpxwantpxwan/article/details/39523403