I have an application that starts a few threads, eventually a thread may need to exit the entire application, however other threads may be in the middle of a task so I'd like to let them continue their current loop before exiting.
In the example below Thread2 has no idea when Thread1 is trying to exit, it simply forces everything to finish right away.
How can I let Thread2, 3 & 4 etc. finish up their loops before shutting down?
Edit: To address the duplicate question concerns: this varies from the typical situation in that the parent class cannot be responsible for puppeteering the shut downs, any of the individual threads must be able to initiate the shut down.
Edit2: I've also left an answer with what I ended up doing which is an implementation of the accepted answer.
class Scratch {
public static void main(String[] args) {
Thread Task1 = new Thread(new Task1());
Task1.start();
Thread Task2 = new Thread(new Task2());
Task2.start();
// ... more threads
}
public class Task1 implements Runnable {
public void run() {
while (true) {
// ...
System.exit(0);
// ...
}
}
}
public class Task2 implements Runnable {
public void run() {
while (true) {
// ...
// I need to know about System.exit(0) to exit my loop
// ...
}
}
}
}