ang*_*iac 8 java multithreading
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%时所做的所有事情的骨架
- >民意调查
- >没有新记录?
- >睡觉
- >重复
检查各个CPU内核的CPU消耗量.如果你使用的是4核机器,也许有一个线程会变得流氓并且正在吃掉核心(25%).这通常发生在线程处于紧密循环中时.
你可以使用Thread.wait
超时(这确实是Timer
类所做的),但我的赌注是它不会有任何区别.无论Thread.sleep
和Thread.wait
改变线程的状态not runnable
.虽然它取决于你的JVM实现等,但在这种情况下线程不应该消耗那么多的CPU.所以我的赌注是工作中存在一些错误.
您可以做的另一件事是进行线程转储,看看线程在发生这种情况时正在做什么.kill -3
如果您使用的是Windows,请在Linux机器上使用,或在java控制台窗口中使用ctrl + break.然后,检查转储到标准输出的线程转储.然后你可以确定线程是否实际上正在睡觉或正在做其他事情.
正如许多人指出的那样,Thread.sleep 应该并且实际上确实有助于大幅降低 CPU 使用率。
我从最初的问题中省略了某些事实,因为我认为它们不相关。
主线程是生产者,还有另一个异步运行的线程是消费者。事实证明,该线程上的“睡眠”处于某种未正确触发的奇怪状态中。因此该线程上的循环从未休眠。
一旦睡眠的东西被消除,我继续仔细分析它以意识到问题。