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);  


你可能感兴趣的:(thread,sleep,running,yield)