Java版本:jdk8
前言
在多線程編程學習的時候,由於理解比較粗淺,故作此文章來加深自己對sleep和wait的理解。關於如何把握sleep和wait的區別的關鍵在於
sleep在Thread中定義,wait在Object中定義。sleep用來操控線程,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.
*/
public static native void sleep(long millis) throws InterruptedException;
-
首先,sleep(long millis)是一個在Thread中聲明的native方法,由底層的C/C++來實現sleep的功能
-
sleep方法jdk注釋,表達的內容
a.當前執行的線程進入指定毫秒數的睡眠狀態, timed_waiting狀態。
b.當前線程不會丟失對象鎖,其他線程依舊無法獲取monitor而無法訪問對象
**補充 **
Thread.sleep(0);
在線程中,調用sleep(0)可以釋放cpu時間,讓線程馬上重新回到就緒隊列而非等待隊列,sleep(0)釋放當前線程所剩余的時間片(如果有剩余的話),這樣可以讓操作系統切換其他線程來執行,提升效率。
wait
/**
* The current thread must own this object's monitor. The thread
* releases ownership of this monitor and waits until another thread
* notifies threads waiting on this object's monitor to wake up
* either through a call to the {@code notify} method or the
* {@code notifyAll} method. The thread then waits until it can
* re-obtain ownership of the monitor and resumes execution.
*/
public final void wait() throws InterruptedException {
wait(0);
}
-
首先,wait是Object中聲明的native方法,由底層的C/C++實現。
-
wait方法的jdk注釋,表達的內容
a.當前正在執行的線程必然是已經擁有了對象的監視器,也就是對象鎖,意味着wait 使用必須配合synchronized一起使用,而sleep 不用。
b.wait會讓線程釋放對Monitor,線程也不可避免的智能進入休眠狀態(waiting 狀態)。其他線程可以訪問該對象。
補充
public final native void wait(long timeout)
// timeout – the maximum time to wait in milliseconds.
// timeout = 0 永遠等待,直到其他線程notify,無限加塞
// timeout > 0 直到其他線程調用此對象的notify()方法或 notifyAll() 方法,或者超過指定的時間量