Restart a died Thread

If a Thread dies the system can inform you via a Thread.UncaughtExceptionHandler. You can use it to restart a Thread:

import java.awt.Frame;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import javax.swing.JDialog;
import javax.swing.JTextArea;

public class Main
{
public static void main( String[] args )
{
ThreadHandler.startThread();
}
}

class ThreadHandler
{
static void startThread()
{
Thread t = new Thread( new MyCommand() );
UncaughtExceptionHandler ueh = new MyUncaughtExceptionHandler();
t.setUncaughtExceptionHandler( ueh );
t.start();
}

static class MyCommand implements Runnable
{
public void run()
{
int i = 0;

System.out.println( 12 / i ); // Provoke a RuntimeException
}
}
}

class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler
{
public void uncaughtException( Thread thread, Throwable throwable )
{
StringWriter stringWriter = new StringWriter();
PrintWriter w = new PrintWriter( stringWriter );
throwable.printStackTrace( w );

JDialog d = new JDialog( new Frame(), true );
d.add( new JTextArea( stringWriter.toString() ) );
d.setTitle( thread.getName() + " --- " + throwable.getMessage() );
d.pack();
d.setVisible( true );

ThreadHandler.startThread(); // Restart Thread
}
}

Ähnliche Beiträge

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert