// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.Semaphore;

import javax.swing.JFrame;

public class RestartableAppMultiThreaded {
    private T1 t1;
    private T2 t2;
    private GUI f;
    private Semaphore sf = new Semaphore(1);
    public void initRestart() {
        t1.interrupt();
        t2.interrupt();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
        }
        f.dispose();
        sf.release();
    }
    public void exec() {
        Thread.setDefaultUncaughtExceptionHandler(new Handler(this));
        while(true) {
            try {
                sf.acquire();
            } catch (InterruptedException e) {
            }
            t1 = new T1();
            t2 = new T2();
            f = new GUI();
            t1.start();
            t2.start();
            f.setVisible(true);
        }
    }
    public static void main(String[] args) {
        RestartableAppMultiThreaded er = new RestartableAppMultiThreaded();
        er.exec();
    }
}

class GUI extends JFrame {
    public GUI() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Some GUI");
        setSize(300, 300);
    }
}

class T1 extends Thread {
    public void run() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
        }
        throw new RuntimeException("Oops");
    }
}

class T2 extends Thread {
    public void run() {
        boolean done = false;
        while(!done) {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                done = true;
            }
        }
        System.out.println("T2 done");
    }
}

class Handler implements UncaughtExceptionHandler {
    private RestartableAppMultiThreaded app;
    public Handler(RestartableAppMultiThreaded app) {
        this.app = app;
    }
    public void uncaughtException(Thread t, Throwable e) {
        app.initRestart();
        System.out.println("Restarting ...");
    }
}
