2

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();
}

}

BartoszCichecki
  • 2,227
  • 4
  • 28
  • 41

2 Answers2

10

You should do it yourself - catch the exception and pass it somehow into the launching thread.

Also, there is Future concept, which does it already. You should launch your threads as futures and check isDone(), and catch ExecutionException from get(), this exception will be thrown if a future's task thrown an exception.

kan
  • 28,279
  • 7
  • 71
  • 101
4

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. Use new Thread(new AnotherClass()).start() instead.

Community
  • 1
  • 1
laguille
  • 637
  • 4
  • 6
  • Yeah, i know, the code above is just a... i would say pseudocode. And what is more, I don't want the main thread to wait for other threads. It has to launch 10 "child" threads, and if no exception occures in these, be able to launch next 10 threads. – BartoszCichecki Nov 11 '11 at 15:54
  • the main thread won't have to wait. It will keep creating threads unless the value of launchNewThread gets changed by one of the child thread via the listener. – laguille Nov 11 '11 at 16:04