You could use multithreading for this:
boolean method2Continue = false;
public void method1() {
// ...
Thread thread = new Thread(() -> method2());
thread.start();
if(keyPressed){
method2Continue = true;
}
thread.interrupt();
// ...
}
public void method2() {
// ...
while(!method2Continue);
// ...
}
After thread.start()
is called, method 1 and method 2 will execute simultaneously, but when method 2 reaches the while loop, it will wait for method2Continue
to be true until it continues on to the next line. At the end of method 1, the method 2 thread will be terminated which will stop its execution.
See a demo here: https://ideone.com/eqnTh7