使用Thread.sleep时线程处于睡眠状态时的CPU消耗 [英] CPU consumption when thread is sleeping using Thread.sleep

查看:1589
本文介绍了使用Thread.sleep时线程处于睡眠状态时的CPU消耗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我有一个服务器程序轮询数据库是否有新请求,我希望此轮询以1分钟的间隔进行,因此,我在while循环的程序中设置了Thread.sleep(). 问题是,每当该程序休眠"时,CPU消耗就会急剧增加(大约25%至30%).
矛盾的是,当程序不处于休眠状态并且正在忙于处理请求时,CPU消耗将降低至0.4%.
我在网上阅读后发现,与thread.sleep相关的性能受到影响,但我找不到任何可行的选择(Thread.wait要求在对象上进行通知,在我的情况下这是无用的)


I have a server program which polls a database for new requests , I want this polling to be done at 1 minute intervals so , I've set up a Thread.sleep() in the program while loop.
The problem is that whenever this program is supposed to "sleep" the CPU consumption goes up drastically (viz. about 25 - 30%).
Paradoxically, when the program is not dormant and is busy processing requests , the CPU consumption drops to 0.4%.
I read online and found out that there are performance hits associated with thread.sleep, but I could not find any viable alternative (Thread.wait requires notification on an object, something which I feel is useless in my scenario)

主循环(没有新请求时)不执行任何操作,这是当CPU消耗为25%时正在执行的所有操作的框架

The main loop (when there are no new requests) doesn't do anything, here is a skeleton of all that is being done when the CPU consumption is 25%

->民意调查
->没有新记录?
->睡眠
->重复

-> poll
-> No new records ?
-> Sleep
->repeat

推荐答案

检查单个CPU内核的CPU消耗是多少.如果您使用的是四核计算机,则可能有一个线程流氓,并且一次吞噬了一个内核(25%).当线程处于紧密循环中时,通常会发生这种情况.

Check what the CPU consumption is for individual CPU cores. If you are using a 4 core machine, maybe one thread is going rogue and is eating up once core (25%). This usually happens when the thread is in a tight loop.

您可以将Thread.wait与超时一起使用(实际上Timer类确实如此),但是我敢打赌,这不会有任何区别. Thread.sleepThread.wait都将线程的状态更改为not runnable.尽管它取决于您的JVM实现等,但是在这种情况下线程不应该消耗那么多的CPU.所以我敢打赌,有一些错误在起作用.

You could use Thread.wait with a timeout (which indeed the Timer class does), but my bet is that it won't make any difference. Both Thread.sleep and Thread.wait changes the threads' state to not runnable. Although it depends on your JVM implementation etc., the thread shouldn't consume that much CPU in such situation. So my bet is that there is some bug at work.

您可以做的另一件事是进行线程转储,并在发生这种情况时查看线程在做什么.在Linux机器上使用kill -3,如果使用Windows,则在Java控制台窗口上使用ctrl + break.然后,检查转储到标准输出的线程转储.然后,您可以确定该线程实际上是在休眠还是在做其他事情.

Another thing you can do is taking a thread dump and see what the thread is doing when this happens. Use kill -3 on a Linux box, or use ctrl+break on the java console window if you are using Windows. Then, examine the thread dump that is dumped to the standard output. Then you can be sure if the thread was actually sleeping or was doing something else.

这篇关于使用Thread.sleep时线程处于睡眠状态时的CPU消耗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆