Thead的yield和sleep的區別

JDK1.5.0的API文檔裏的描述:

yield:Causes the currently executing thread object to temporarily pause and allow other threads to execute.

sleep:Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.

根本無助於理解兩者間的差別



線程的生命週期裏有三個狀態Runable、Blocked、Running

yield:Running  ->  Runable

sleep: Running -> Blocked -> Runable

yield和sleep都是在線程處於Running的時候開始的,yield只是讓出分配給自己的CPU時間片,並且會立刻進入Runable狀態參與CPU時間的競爭,若程序中沒有其他線程,那麼該線程馬上就會開始往下執行;sleep會進入Blocked狀態,等待時間結束事件的發生,然後進入Runable狀態參與CPU時間的競爭



另外,sleep和yield都不具備同步語義,也就是說編譯器在執行sleep或yield方法之前和之後,都沒有強制要求同步本地緩存與主存的數據

以下摘自JSL3.0





It is important to note that neither Thread.sleep nor Thread.yield have

any synchronization semantics. In particular, the compiler does not have to flush

writes cached in registers out to shared memory before a call to Thread.sleep or

Thread.yield, nor does the compiler have to reload values cached in registers

after a call to Thread.sleep or Thread.yield.





For example, in the following (broken) code fragment, assume that this.done is a non-volatile

boolean field:

   while (!this.done)  
       Thread.sleep(1000);  


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