Reputation: 70997
How can I switch back to main thread from a different thread when there is an exception. When an exception is raised on a child thread, I want a notification to be sent to main thread and execute a method from the main thread. How can I do this?
Thanks.
Additional information
I am calling a method from my main method and starting a new thread there after some calculations and changes
Thread thread = new Thread() {
@Override
public void run() {
.....
}
}
thread.start();
Upvotes: 6
Views: 8614
Reputation: 10493
Implement the interface http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.UncaughtExceptionHandler.html in some class of your application, and let it deal with the thread and the exception it generated.
See the document for more details.
EDIT: This is probably not what you wanted - I believe the method is going to be called by the thread that just threw the exception. If you want some method to be executed on your main thread (in its context), the main thread will have to be waiting for it somehow.
But if you only want to handle the exception that's one case. The best approach, thought, would be to handle the exception in a try...catch block inside your thread.
Upvotes: 0
Reputation: 44821
As TofuBeer says you need to provide more context, if however that context is that you're a swing app...
SwingUtilities.invokeLater(Runnable r) allows you to call back on Swing's main execution thread.
} catch (final Exception e) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
//do whatever you want with the exception
}
});
}
Upvotes: 3
Reputation: 61526
This might work for you.
public class Main
{
public static void main(final String[] argv)
{
final Main main;
main = new Main();
main.go();
}
public void go()
{
final Runnable runner;
final Thread thread;
runner = new Foo(this);
thread = new Thread(runner);
thread.start();
}
public void callback()
{
System.out.println("hi!");
}
}
class Foo
implements Runnable
{
private final Main main;
Foo(final Main m)
{
main = m;
}
public void run()
{
// try catch and handle the exception - the callback is how you notify main
main.callback();
}
}
Upvotes: -2
Reputation: 28752
When the exception occurs in the child thread, what is the main thread going to be doing? It will have to be waiting for any errors in a child thread.
You can establish an UncaughtExceptionHandler
in the child thread, which can raise an event that the main thread is waiting for.
Upvotes: 3
Reputation: 199224
If your child thread was created in the main, you might leave the exception pop up and handle it on the main thread.
You can also put a sort of call back.
I haven't tried this my self though.
Upvotes: 1