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
}
}
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.
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.
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.