標籤:
類的區別
- wait()來自於
java.lang.Object,任何對象都有此方法
- sleep()來自於
java.lang.Thread,調用的對象為線程
用法上的區別
看一下jdk的描述:
wait():Causes the current thread to wait until either another thread invokes the
java.lang.Object.notify() method or the java.lang.Object.notifyAll()method for this object, or a specified amount of time has elapsed.
使當前線程掛起,當對象調用java.lang.Object.notify()或者java.lang.Object.notifyAll()或者時間到期,則從wait()中恢複執行
sleep():Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.
在指定的時間內使當前執行的線程睡眠(暫停執行)
同步與鎖的不同
wait()與sleep()最主要的區別就在於同步與鎖,wiat()必須放在synchronized block中,否則會在program runtime時扔出java.lang.IllegalMonitorStateException異常。
一般而言,wait()用於線程間的通訊,sleep()用於線程狀態的控制
參考資料
http://stackoverflow.com/questions/1036754/difference-between-wait-and...
http://howtodoinjava.com/2013/03/08/difference-between-sleep-and-wait/
http://www.qat.com/using-waitnotify-instead-thread-sleep-java/
Java中wait()與sleep()的區別