简体   繁体   English

偶尔执行一次

[英]Only execute once in a while loop

I have a method to add objects to a queue and also check the queue size. 我有一种将对象添加到队列并检查队列大小的方法。 If the queue size hits max capacity, an alarm will be raised and the queue will remove the first object. 如果队列大小达到最大容量,将发出警报,并且队列将删除第一个对象。 Following is the code 以下是代码

private SomeQueue queue;
private boolean raiseAlarmOnce = true;
private boolean alarmRaised;
private AlarmConnection alarmConnection;

void addToQueue(Object obj) {

     queue.add(obj);

     while (queue.size() > 1000) {
         queue.remove(); 

         if (m_raiseAlarmOnce) {
            // raiseAlarm mtheod will return boolean value to indicate 
            // the result of raising alarm
            m_alarmRaised = alarmConnection.raiseAlarm();
            raiseAlarmOnce = false;
         }
      }
      m_raiseAlarmOnce = true;

      if (m_alarmRaised) {
         alarmConnection.clear();
         m_alarmRaised = false;
      }
   }

If the queue size is bigger than 1000, the queue will continually delete obj and only raise the alarm once. 如果队列大小大于1000,则队列将不断删除obj,并且仅引发一次警报。 If the alarm raised successfully, the alarm will be cleared. 如果警报成功发出,则警报将被清除。 Just want to know any better way to do this? 只想知道任何更好的方法吗?

if you need raise alarm once, when queue size is 1001, 1002 etc instead of one time for each iteration, raise alarm out of the while using a flag 如果您需要一次发出警报,则在队列大小为1001、1002等而不是每次迭代一次的情况下,请在使用标志的同时发出警报

i suggest use local variables when works with threads or singletons isntances 我建议在使用线程或单例等距时使用局部变量

void addToQueue(Object obj) {

     queue.add(obj)
     boolean raisAlarm = false;

     while (queue.size() > 1000) {
         queue.remove(); 
         raisAlarm  = true;
      }


      if (raisAlarm) {
            // raiseAlarm mtheod will return boolean value to indicate 
            // the result of raising alarm
            boolean m_alarmRaised = alarmConnection.raiseAlarm();
            if (m_alarmRaised) {
              alarmConnection.clear();
            }
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM