Thread.yield() 与 Thread.sleep()的区别

本文探讨了游戏模拟器KEmulator中EventQueue重构后导致CPU使用率过高的问题,并通过对比Thread.yield()与Thread.sleep(1)的效果,发现后者能有效降低CPU使用率。在特定条件下,使用Thread.sleep(1)替代Thread.yield()可以解决内存限制引起的操作延迟。

From: http://www.j2megame.org/index.php/content/view/1608/125.html

 

I refactor the EventQueue in KEmulator, then test on some games.

when running MI3 and Gangstar, the CPU reached 100% utilization.

and after testing, i got my answer, cause of Thread.yield() in run() with a while(true) circle.

 

So i made a test, preReplace all the Thread.yield() with Thread.sleep(1) in game loading. this time, everything goes good. the MI3 got a lower 10% CPU utilization in average.

  • sleep() will let your thread do nothing for a certain amount of time. Basically, your thread can’t do anything until it is done sleeping.
  • yield() will cause your thread to voluntarily let other threads in your program run. If no other threads are ready to run, then your thread will continue.

Thread.yield() will help your thread give time to other threads, but when other threads are free or yield()ing will still take up 100% of the CPU. Otherwise, Thread.sleep() is the only way to force the CPU getting a rest.

 

=======================

May be there is a same case in Mobile development.

In some handset, when the game reaches the memory limit, the key events will cause an obviously delay. In Realfootball team last year, i found out that calling more Thread.yield()(two or three) in the run() circle can solve the problem.

Maybe one Thread.sleep(1) did the job here.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值