简体   繁体   中英

How to stop a runnable within the 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?
            }
        }
    }
}

You can break the loop if health < 1:

if (health < 1) {
    break;
}

Or you can change the while condition:

while (health > 1) {

}
while (true) {
    if (health < 1) {
        // How do i stop the runnable?
        return;
    }
}

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