Return to main thread?

How can I return to the main thread from another thread when there is an exception. When an exception occurs in the child thread, I want the notification to be sent to the main thread and execute the method from the main thread. How can i do this?

Thanks.

Additional Information

I call the method from my main method and start a new thread there after some calculations and changes

Thread thread = new Thread() { @Override public void run() { ..... } } thread.start(); 
+6
java multithreading
source share
5 answers

When an exception occurs in a child thread, what will be the main thread? It will have to wait for any errors in the child thread.

You can set an UncaughtExceptionHandler in a child thread that can raise an event that the main thread is expecting.

+3
source share

As TofuBeer says you need to provide more context if, however, this context is that you are a swing application ...

SwingUtilities.invokeLater (Runnable r) allows you to return to the main Swing execution thread.

 } catch (final Exception e) { SwingUtilities.invokeLater(new Runnable(){ public void run() { //do whatever you want with the exception } }); } 
+3
source share

If your child thread was created mainly, you can leave a pop-up exception and handle it in the main thread.

You can also put a callback.

I have not tried this myself, though.

+1
source share

Deploy the http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.UncaughtExceptionHandler.html interface in some class of your application and let it handle the thread and the exception it throws.

See the document for more details.

EDIT: This is probably not what you wanted - I believe the method will be called by a thread that just threw an exception. If you want some method to be executed in the main thread (in its context), the main thread had to wait for it somehow.

But if you want to handle an exception in only one case. The best approach, I thought, is to handle the exception in the try ... catch block inside your thread.

0
source share

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

All Articles