Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - switching back to main thread?

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();
like image 804
lostInTransit Avatar asked Mar 05 '09 06:03

lostInTransit


3 Answers

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.

like image 150
Miserable Variable Avatar answered Oct 19 '22 16:10

Miserable Variable


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
        }
    }); 
}
like image 28
Tom Avatar answered Oct 19 '22 18:10

Tom


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.

like image 34
OscarRyz Avatar answered Oct 19 '22 17:10

OscarRyz