Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a runnable within the runnable?

Tags:

java

runnable

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?
            }
        }
    }
}
like image 656
Potato Avatar asked Oct 26 '25 08:10

Potato


2 Answers

You can break the loop if health < 1:

if (health < 1) {
    break;
}

Or you can change the while condition:

while (health > 1) {

}
like image 99
DontPanic Avatar answered Oct 27 '25 23:10

DontPanic


while (true) {
    if (health < 1) {
        // How do i stop the runnable?
        return;
    }
}
like image 44
Vyacheslav Avatar answered Oct 28 '25 00:10

Vyacheslav