區別
- 這兩個方法來自不同的類分別是Thread和Object
- 最主要是sleep方法沒有釋放鎖,而wait方法釋放了鎖,使得其他線程可以使用同步控制塊或者方法(鎖代碼塊和方法鎖)。
- wait,notify和notifyAll只能在同步控制方法或者同步控制塊里面使用,而sleep可以在任何地方使用(使用范圍)
- sleep必須捕獲異常,而wait,notify和notifyAll不需要捕獲異常
例子
package wait_sleep; /** * java中的sleep()和wait()的區別 * @author Hongten * @date 2013-12-10 */ public class TestD { public static void main(String[] args) { new Thread(new Thread1()).start(); try { Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); } new Thread(new Thread2()).start(); } private static class Thread1 implements Runnable{ @Override public void run(){ synchronized (TestD.class) { System.out.println("enter thread1..."); System.out.println("thread1 is waiting..."); try { //調用wait()方法,線程會放棄對象鎖,進入等待此對象的等待鎖定池 TestD.class.wait(); } catch (Exception e) { e.printStackTrace(); } System.out.println("thread1 is going on ...."); System.out.println("thread1 is over!!!"); } } } private static class Thread2 implements Runnable{ @Override public void run(){ synchronized (TestD.class) { System.out.println("enter thread2...."); System.out.println("thread2 is sleep...."); try { //在調用sleep()方法的過程中,線程不會釋放對象鎖。 Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); } System.out.println("thread2 is going on...."); System.out.println("thread2 is over!!!"); //如果我們把代碼:TestD.class.notify();給注釋掉,即TestD.class調用了wait()方法,但是沒有調用notify() //方法,則線程永遠處於掛起狀態。 TestD.class.notify(); } } } }