Programmer's Blog

Programmer's reference

[Java] Stop all threads when first finishes

1. Firstly declare a static boolean variable to be shared by all threads in the Thread class

class MyThread implements Runnable {
   ..
    static boolean stop = false;
}

2. Then in the run() method set stop to true immediately when loop finishes

public void run() {
    do{
          .....

    } while (stop == false && count < 100);
    stop = true;
}

3. perform checking in other threads for the static boolean, break the loop if stop is true

public void run() {
    do {
        ..
        if (stop == true) then break;
    }
}

Leave a comment