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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值