简体   繁体   中英

Java | Terminating all child threads if parent thread is terminated

Please help me with this Main thread/ Parent thread will triggers sub threads. If we are stopping parent/main thread it must also stop all child/sub threads

I am thinking to do it with interrupts but not able to do it Please help me out with the code

and how to ensure all child threads have been stopped?IS there any way to do this also

Thanks in Advance!

I am trying to do something like this :

public class ThreadTest1 extends Thread{ private static final Logger LOGGER = Logger.getLogger("mylogger");

public void run(){  


      for(int i=1;i<=5;i++){  
       try{  
           if (!Thread.currentThread().isInterrupted()) {
               LOGGER.log(Level.SEVERE,"Sleeping...");
               Thread.sleep(1000);
               LOGGER.log(Level.SEVERE,"Processing");
               System.out.println(Thread.currentThread().getId()+"Thread id:    "+i);  
           }
           else{
               throw new InterruptedException();
           }




       }catch(InterruptedException e){
           System.out.println(e);
           LOGGER.log(Level.SEVERE,"Exception", e);
           Thread.currentThread().interrupt();

       }  

      }  
     }  
    public static void main(String args[]){  

        ThreadTest1 t1=new ThreadTest1();  
        ThreadTest1 t2=new ThreadTest1();  
        ThreadTest1 t3=new ThreadTest1();  
        System.out.println(t1.getId());
        System.out.println(t2.getId());
        System.out.println(t3.getId());

        t1.start();  
        t2.start();  
        t3.start();
        System.out.println("Do you want to kill all processes: Press any key to continue");
        int s=0;
        try {
            s = System.in.read();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
            if(s!=0){

            t1.interrupt();
            t2.interrupt();
            t3.interrupt();
        }

            System.out.println(t1.isAlive());

     }  

}

Java automatically groups Threads. If you do not define a specific ThreadGroup, it will always grouped as child of the thread where the initialization takes place.

So if you abort a parent Thread, all its childThreads will be aborted too.

perhaps this could help (sorry that it's in german): dpunkt programming pdf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM