我们注意到我们的应用程序在Linux中消耗了99%的CPU周期,并且我们发现一个线程在一个无限循环中运行,这导致了这个问题。我们注意到了一个奇怪的行为。基于参数,该线程调度计时器任务。如果计划了计时器任务,则CPU使用率降至20%。如果不是预定的CPU使用率是100%。只是想知道引入另一个处理线程如何将CPU使用率降低到10-20%。
public void run()
{
log.info("Starting VCMG Channel Thread...");
while (true) {
if (readPacket()) {
LoyaltyMessageHandle mh = null;
synchronized(this)
{
if(map.containsKey(respSTAN))
{
mh = (LoyaltyMessageHandle) map.get(respSTAN);
mh.setLoyaltyResp(loyaltyObject);
resetHeartBeatTimer();
}
else
{
//Just drop the packet on the floor... It probably timedout.
if (!log.isDebugEnabled())
{
log.warn("Packet: [" + new String(loyaltyObject).substring(0,28) +
"...] DROPPED !!!!!");
}
else
{
log.debug("Packet: [" + new String(loyaltyObject) + "] DROPPED !!!!!");
}
}
}
if(mh != null) {
synchronized(mh) {
mh.notify();
}
}
}
}
}
public synchronized void resetHeartBeatTimer()
{
if (heartBeatTimer != null)
{
heartBeatTimer.cancel();
}
startHeartBeat();
}
public synchronized void startHeartBeat()
{
heartBeatTimeOut = loyaltyMgr.getHeartBeatInactiveTimer() * 1000;
// Timeout value zero indicates that the 'heartbeat' needs to be disabled.
// If the timeout value is less than zero that should be ignored since that will cause exception.
if ((heartBeatTimeOut > 0) && (this.clientSocket.isConnected()))
{
if (heartBeatTimeOut < HEART_BEAT_LOWEST_TIMEOUT)
{
heartBeatTimeOut = HEART_BEAT_LOWEST_TIMEOUT;
}
heartBeatTimer = new HeartBeatTimer(this, loyaltyMgr.getHeartbeatTimeout());
Timer timer = new Timer();
timer.schedule(heartBeatTimer, heartBeatTimeOut);
}
}
答案 0 :(得分:4)
因为如果一个循环运行紧张而没有“睡眠”,那么它只是使用CPU
如果您进入睡眠状态或以其他方式与该线程争用,则CPU未被使用
您的计时器必须在循环中休眠,因此使用较少的CPU时间