简体   繁体   English

Java | 如果终止父线程,则终止所有子线程

[英]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"); 公共类ThreadTest1扩展了线程{私有静态最终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. Java自动将线程分组。 If you do not define a specific ThreadGroup, it will always grouped as child of the thread where the initialization takes place. 如果未定义特定的ThreadGroup,它将始终分组为进行初始化的线程的子代。

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 也许这可能会有所帮助(对不起,它是德语): dpunkt programming pdf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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