4

I'm trying to create a runnable that will test to see if you're dead (health below 1) and if you are dead, then it will stop the runnable. If you aren't it will keep going. But I can't find a way to stop the runnable. Is there any way to stop the runnable within the runnable with a script?

Note that the runnable is being run through a thread:

Thread thread1 = new Thread(runnableName);
thread1.start();

Runnable Example:

Runnable r1 = new Runnable() {
    public void run() {
        while (true) {
            if (health < 1) {
                // How do i stop the runnable?
            }
        }
    }
}
Potato
  • 49
  • 2
  • 9
  • 5
    You don't have to do anything special, just reach the end of your `run` method and the thread will terminate. – Welbog Apr 17 '17 at 21:02
  • The script that checks to see if you're dead is in a while loop. – Potato Apr 17 '17 at 21:03
  • 3
    So exit the while loop. – Welbog Apr 17 '17 at 21:03
  • In that case, you can either add a volatile boolean that would break your loop, or interrupt a thread that runs your code. – M. Prokhorov Apr 17 '17 at 21:04
  • make sure there is some synchronization while checking health – bichito Apr 17 '17 at 21:04
  • Why do you need a separate thread to check for deadness? Shouldn't you just check it whenever health is decreased, and if it's below 1 you set some `isDead` variable to `true`, which would affect a `while(!isDead)` loop in some relevant part of your code. – Kayaman Apr 17 '17 at 21:05
  • Take a look at this: http://stackoverflow.com/questions/10630737/how-to-stop-a-thread-created-by-implementing-runnable-interface – edu_ Apr 17 '17 at 21:08
  • https://github.com/ReactiveX/RxJava if you can i'd highly recommend moving to this. – JakeWilson801 Apr 17 '17 at 21:17

2 Answers2

2

You can break the loop if health < 1:

if (health < 1) {
    break;
}

Or you can change the while condition:

while (health > 1) {

}
DontPanic
  • 1,327
  • 1
  • 13
  • 20
1
while (true) {
    if (health < 1) {
        // How do i stop the runnable?
        return;
    }
}
xlm
  • 6,854
  • 14
  • 53
  • 55
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194