如何终止子级的父线程? [英] How do I terminate parent thread from child?
问题描述
如何从创建主线程的子线程中终止父线程(主线程)?我尝试了System.exit(1),但它仅终止子线程.我还尝试过将条件放入main的while循环中,但显然它将在退出前尝试读取1个额外的输入.
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.
相反,您应该向另一个线程发送信号(使用多种方法中的任何一种),然后该线程退出自身.要退出线程,只需从线程的run方法返回即可.
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.
这篇关于如何终止子级的父线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!