-3

Is there a possibility to break a while-loop immediately after the condition gets false?

while(true){
//Backgroundtask is handling appIsRunning boolean
            while (appIsRunning) {
                Roboter.movement1(); //while Roboter.movement1 is running appIsRunning changes to false

                Roboter.movement2();
            }
            while (!appIsRunning) {
            //wait for hardbutton/backgroundtask to set appIsRunning true
            }

    }   

I don't want to wait until the first movement is done, the while should break immediatelty and closes the Roboter.class. And I dont want to check inside the Roboter.class if appIsRunning is true...

Waeuk
  • 21
  • 3

3 Answers3

0

Cleanest way to do it without re-thinking your "architecture" (which I would suggest, but depends on what you're trying to achieve would be to do:

while(true){
    while (appIsRunning) {
        if(!Roboter.movement1()) { //Hardbutton is pressed to stop application / appIsRunning is false
            break;
        }
        Roboter.movement2();
    }
    while (!appIsRunning) {
        //wait for hardbutton/backgroundtask to set appIsRunning true
    }
}

And returning false from "movement1()" when you want to leave...

andredp
  • 33
  • 4
0

If you want to completele stop Roboter.movement1() execution immideatly, you should use another thread and execute it there:

Thread mover = new Thread() {
        @Override
        public void run() {
            Roboter.movement1();
        }
    }
mover.start();

and when you need to stop, use mover.stop();

Carefull: using stop() may cause wrong behaviour of your program How do you kill a thread in Java?

TEXHIK
  • 1,369
  • 1
  • 11
  • 34
  • @Waeuk and consider, that `Thread.start() ` method is NOT blocking, so after the thread is started main thread will continue to execute. – TEXHIK Nov 22 '17 at 11:21
-1

type break; where the condition fails! simple!