I am writing an app that will make use of multiple threads. There is main thread that is launching another threads. What i want to acomplish is when one of the launched threads throws an exception, the main thread should stop launching threads. It looks more or less like this:
class SomeClass {
boolean launchNewThread = true;
public static void main() {
while (launchNewThread) {
try {
AnotherClass.run();
} catch (CrossThreadException e) {
launchNewThread = false;
}
}
}
}
class AnotherClass implements Runnable {
public void run() {
if (a=0) throw new CrossThreadException();
}
}
You can also use a listener as described in How to throw a checked exception from a java thread?
When an exception is thrown inside one of the child threads, you could call a method like
listener.setLaunchNewThread(false)from the child thread which will change the value of your boolean flag in the parent thread.On a side note, calling
AnotherClass.run()does not start a new thread but only call the run method from AnotherClass within the same thread. Usenew Thread(new AnotherClass()).start()instead.