本質上就是:sleep是Thread類的方法,wait是Object類中定義的方法
JavaDoc中說到:
A thread becomes the owner of the object's monitor in one of three ways:
1. By executing a synchronized instance method of that object.
2. By executing the body of a synchronized statement that synchronizes on the object.
3. For objects of type Class, by executing a synchronized static method of that class.
通過以下三種方法之一,線程可以成爲此對象監視器的所有者:
- 通過執行此對象的同步 (Sychronized) 實例方法。
- 通過執行在此對象上進行同步的 synchronized 語句的正文。
- 對於 Class 類型的對象,可以通過執行該類的同步靜態方法。
========================================================================
sleep 讓線程從 【running】 -> 【阻塞態】 時間結束/interrupt -> 【runnable】
wait 讓線程從 【running】 -> 【等待隊列】notify -> 【鎖池】 -> 【runnable】
代碼示例:
exapmle 1,鎖定方法所屬的實例對象:
public synchronized void method(){
//然後就可以調用:this.notify()...
//或者直接調用notify()...
}
exapmle 2,鎖定方法所屬的實例的Class:
public Class Test{
public static synchronized void method(){
//然後調用:Test.class.notify()...
}
}
exapmle 3,鎖定其他對象:
public Class Test{
public Object lock = new Object();
public static void method(){
synchronized (lock) {
//需要調用 lock.notify();
}
}
}
總結:
:“線程操作的wait()、notify()、notifyAll()方法只能在同步控制方法或同步控制塊內調用。如果在非同步控制方法或控制塊裏調用,程序能通過編譯,但運行的時候,將得到 IllegalMonitorStateException 異常,並伴隨着一些含糊信息,比如 ‘當前線程不是擁有者’。其實異常的含義是 調用wait()、notify()、notifyAll()的任務在調用這些方法前必須 ‘擁有’(獲取)對象的鎖。
參考:java api
http://blog.csdn.net/Wen_Demo/article/details/41974623
http://blog.csdn.net/intlgj/article/details/6245226