在循环中停止java定时器以同时执行

时间:2015-02-10 20:09:12

标签: arrays loops timer

请稍微帮帮忙。如何使它按以下顺序工作:检查一个i的值,为它运行Timer,只有当该计时器完成时,做i ++?目前,两个计时器同时运行。试图声明boolean isRunning,但没有帮助。

for(int i=0;i<pcArray.length;i++){            
            if(pcArray[i]==1){
               blinkGreen.start();            }
            else if(pcArray[i]==2){
                blinkRed.start();               
            }
        }

1 个答案:

答案 0 :(得分:0)

首先在blinkGreen和blinkRed Timer中添加一个布尔变量,如下所示,

在BlinkGreen中:

boolean isRunningGreen = false;
  Timer blinkGreen = new Timer();      
  TimerTask task = new TimerTask() {

     @Override
     public void run() {
        // do stuff
        isRunningGreen = true;//This statement must be placed at the end/bottom of this method 
     }
  };

在BlinkRed中:

  boolean isRunningRed = false;
  Timer blinkRed = new Timer();      
  TimerTask task = new TimerTask() {

     @Override
     public void run() {
        // do stuff
        isRunningRed = true;//This statement must be placed at the end/bottom of this method 
     }
  };

现在试试这个:

for(int i=0;i<pcArray.length;i++){            
            if(pcArray[i]==1){
               blinkGreen.start();  
               while(!isRunningGreen){}//waiting until the task is completed
            } else if(pcArray[i]==2){
               blinkRed.start();
               while(!isRunningRed){}//waiting until the task is completed               
            }
}