How do I terminate parent thread from child?

佐手、 提交于 2019-12-11 03:25:13

问题


How do I terminate the parent (main) thread from a child thread created my main? I tried System.exit(1) but it only terminate the child thread. I also tried putting a condition in main's while loop but it will obviously try to read 1 extra input before exiting.

public static void main(String[] args) throws IOException
{
    new Thread(new Runnable() 
    { 
      public void run() 
      { 
        while(true) 
        { 
            //meet a condition then terminate
        } 
      } 
    }).start(); 
    while (true)
    {
        String a = input.nextLine();
        //do something with input
    }
}

回答1:


You shouldn't do this. It's a really bad idea to terminate any thread from outside that thread. This is because the terminating thread has no idea what the target is doing and whether it is at a "safe" point to terminate. For example you might be in the middle of writing output, or making calculations, or anything.

Instead you should send a signal to the other thread (using any one of a number of means) and that thread exits itself. To exit a thread just return from the thread's run method.




回答2:


Kill a Thread from it's children it's not a good practice, but you can program the children thread to update a field from the parent. if this field is not null parent should stop.

Also take a look to this question



来源:https://stackoverflow.com/questions/29892984/how-do-i-terminate-parent-thread-from-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!