`
nada_forever
  • 浏览: 24120 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

【转】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:

 

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

 

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.

 

原文地址:http://blog.csdn.net/kingquake21/archive/2011/01/24/6160952.aspx

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics