简体   繁体   中英

Java - wait in for loop until method finishes, then continue

I need to run through a for loop where the text of a JLabel is set with the counter variable i and after that a Timer method is called. I now want the loop to wait until the method finishes.

Code:

public void actionPerformed(ActionEvent arg0) {
    for (int i = 1; i < 6; i++) {
        labelNr.setText(Integer.toString(i));
        startTimer();
    }           
}

Because what it does now is that it instantly sets the text of the JLabel to 5, because it runs through the loop, but starting the timer just in the first loop.

I want the text of the JLabel to be 1 for the first loop, then call the Timer method, then 2 for the second loop, again Timer, 3 for the third loop and so on.

It basically just needs to wait until the startTimer() method has finished its execution. I know that synchronized is the possible solution, but I do not know how to implement it properly...

Thanks in advance.

OK, since I want a quick and dirty answer, it was voted down. So how about this:

public void actionPerformed(ActionEvent arg0) {
    changeLabelAndExecuteTask(1)
}

public void changeLabelAndExecuteTask(int i){
    labelNr.setText(Integer.toString(i));
    startTimer(i);
}
public void startTimer(final int i){
    //start a timer here
    new Timer().schedule(new TimerTask(){ 
        @Override 
        void run(){
            methodTimerCall(i)
        }}, 0);
}

public void methodTimerCall(int i){
    //execute things here
    if(++i < 6){
        changeLabelAndExecuteTask(i);
    }
}

forget the under part

You can add a static boolean and reset it value by the timer:

bool waitForTimer = false;
public void actionPerformed(ActionEvent arg0) {
    for (int i = 1; i < 6; i++) {
        waitForTimer = true;
        labelNr.setText(Integer.toString(i));
        startTimer();
        while(waitForTimer){}
    }
}
public void startTimer(){
    //start a timer here
}

public void methodTimerCall(){
    //execute
    waitForTimer = false;
}

一种有效的方法可能是将代码放在 for 循环中的单独方法中,并让“startTime()”方法在执行结束时调用此方法。这样可以保证它在方法完成时准确运行, 而不是在任意时间(即使用 Thread.sleep();)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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