2

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
    }
}
Toan Le
  • 412
  • 1
  • 6
  • 17
  • 1
    `System.exit(1)` terminates _all_ threads. To answer your question, you cannot - `input.nextLine` is **blocking** and **non-interruptible** so once you start waiting for input you cannot stop. – Boris the Spider Apr 27 '15 at 10:20
  • if I do the opposite, calling System.exit(1) in main's while loop, will it terminate the child? – Toan Le Apr 27 '15 at 10:30
  • 1
    From [the documentation](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#exit-int-): _Terminates the currently running Java Virtual Machine._ `System.exit` exits the whole JVM. **All** threads exit. The JVM terminates. That's it. You shouldn't be using it in any case - there is almost never a good use case for it. – Boris the Spider Apr 27 '15 at 10:51
  • B.T.W., "Parent" and "Child" have no meaning in Java threading. Thread _groups_ can have a parent/child relationship, and every Thread belongs to a ThreadGroup, but if thread A creates thread B, the library does not grant either thread any special rights, or capabilities with respect to the the other, nor does it remember which one created which. – Solomon Slow Apr 27 '15 at 13:09

2 Answers2

5

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.

Tim B
  • 40,716
  • 16
  • 83
  • 128
  • Thanks for the explanation. I might have to try a different way for server to signal the client when it's safe to exit then. I always encounter some socketbinding exception when the client exits first. Also, if I end the parent (main) thread, will it terminate the child's thread? – Toan Le Apr 27 '15 at 10:27
1

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

Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109