wait(1000) vs sleep(1000) 線程面試題

Thread.Sleep(1000) 意思是在未來的1000毫秒內本線程不參與CPU競爭,1000毫秒過去之後,這時候也許另外一個線程正在使用CPU,那麼這時候操作系統是不會重新分配CPU的,直到那個線程掛起或結束,即使這個時候恰巧輪到操作系統進行CPU 分配,那麼當前線程也不一定就是總優先級最高的那個,CPU還是可能被其他線程搶佔去。另外值得一提的是Thread.Sleep(0)的作用,就是觸發操作系統立刻重新進行一次CPU競爭,競爭的結果也許是當前線程仍然獲得CPU控制權,也許會換成別的線程獲得CPU控制權。

wait(1000)表示將鎖釋放1000毫秒,到時間後如果鎖沒有被其他線程佔用,則再次得到鎖,然後wait方法結束,執行後面的代碼,如果鎖被其他線程佔用,則等待其他線程釋放鎖。注意,設置了超時時間的wait方法一旦過了超時時間,並不需要其他線程執行notify也能自動解除阻塞,但是如果沒設置超時時間的wait方法必須等待其他線程執行notify


1、wait()方法來自於Object類,而sleep()方法來自於Thread類

//wait
public final void wait()  throws InterruptedException
//sleep
public static native void sleep(long millis) throws InterruptedException;

2、wait() 方法必須在同步代碼塊中調用,否則會拋出異常IllegalMonitorStateException; 而sleep()則不會。

IllegalMonitorStateException - if the current thread is not the owner of the object's monitor.

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

 synchronized (obj) {
     while (<condition does not hold>)
         obj.wait();
     ... // Perform action appropriate to condition
 }

3、sleep不會釋放鎖,它也不需要佔用鎖。wait會釋放鎖,但調用它的前提是當前線程佔有鎖(即代碼要在synchronized中)


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章