Anmutig Herunterfahren ein Programm mit mehreren threads mit unendlichen while-Schleife

Ich habe ein Programm erstellt 10 threads, und jeder thread hat eine endlos laufende while-Schleife.
Ich brauche Hilfe, um effizient zu implementieren, ein Shutdown-hook, mit dem wirksam BEENDEN aller threads. Da will ich tun, um ein ordnungsgemäßes Herunterfahren jeder Thread beendet werden soll, sobald er feststellt das stop-flag gesetzt hat, zu WAHREN.

public class SampleGSH implements Runnable{
    private static boolean stop = false;
    public static void main(String[] args) {
        for(int i = 0; i < 10;i++) {
            Thread t = new Thread(new SampleGSH(), "name"+i);
            t.start();
        }
    }

    @Override
    public void run() {
            Runtime.getRuntime().addShutdownHook(new Thread("shutdown thread") {
                public void run()
                {
                    System.out.println("*******");
                    synchronized (this) 
                    {
                        System.out.println("Turning switch off");
                        stop = true;
                    }
                }
            });

            synchronized (this) {
                while(!stop)
                {
                      //Some logic which should not be killed abruptly once it starts running, a graceful shut down will not allow this code to start
                }
            }   
    }
}

Jede Hilfe wird wirklich geschätzt.

InformationsquelleAutor Suyog Barve | 2013-05-05
Schreibe einen Kommentar