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:
The compiler is free to read the field this.done just once, and reuse the cached value
in each execution of the loop. This would mean that the loop would never terminate, even if
another thread changed the value of this.done.
本文详细解析了Java线程API文档中的yield和sleep方法,对比了它们在线程生命周期中的不同作用,特别是如何影响线程的运行状态以及与CPU时间竞争的关系。同时指出这两种方法在执行前后都不具备同步语义,强调了它们在多线程环境下的使用注意事项。
165

被折叠的 条评论
为什么被折叠?



