Java多线程系列(一)yield

本文探讨了Java中Thread类的yield()方法,解释了其作为礼让调度的暗示作用,强调了此方法的使用场景有限,并通过实例展示了yield()方法的实际效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

yield方法是Thread类的静态方法,也是一个native方法。

调用方式:Thread.yield();

java源码中对这个方法的注释是:

 A hint to the scheduler that the current thread is willing to yield
* its current use of a processor. The scheduler is free to ignore this
* hint.

 

简单来说,就是礼让下。

源码注释也说了:

It is rarely appropriate to use this method.

也就是说,这个方法使用场景不多。

可以参考这篇文章:http://www.importnew.com/14958.html

通过这篇文章的这个例子可以对yield方法有点深入的理解

 

不过按照上面那篇文章运行下来,yield后我的电脑打印结果还是

2019-05-09 15:04:59.710 19347-19369/calc.superdy.myapplication I/System.out: I am Producer : Produced Item 0
2019-05-09 15:04:59.710 19347-19369/calc.superdy.myapplication I/System.out: I am Producer : Produced Item 1
2019-05-09 15:04:59.710 19347-19369/calc.superdy.myapplication I/System.out: I am Producer : Produced Item 2
2019-05-09 15:04:59.710 19347-19369/calc.superdy.myapplication I/System.out: I am Producer : Produced Item 3
2019-05-09 15:04:59.710 19347-19369/calc.superdy.myapplication I/System.out: I am Producer : Produced Item 4
2019-05-09 15:04:59.711 19347-19370/calc.superdy.myapplication I/System.out: I am Consumer : Consumed Item 0
2019-05-09 15:04:59.711 19347-19370/calc.superdy.myapplication I/System.out: I am Consumer : Consumed Item 1
2019-05-09 15:04:59.711 19347-19370/calc.superdy.myapplication I/System.out: I am Consumer : Consumed Item 2
2019-05-09 15:04:59.711 19347-19370/calc.superdy.myapplication I/System.out: I am Consumer : Consumed Item 3
2019-05-09 15:04:59.711 19347-19370/calc.superdy.myapplication I/System.out: I am Consumer : Consumed Item 4
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值