如何终止子线程的父线程?

Toa*_* Le 2 java concurrency multithreading exit

如何从我创建的子线程中终止父(主)线程?我试过System.exit(1),但它只终止子线程.我也尝试在main的while循环中设置一个条件,但显然会在退出之前尝试读取1个额外的输入.

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
    }
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*m B 5

你不应该这样做.从该线程外部终止任何线程是一个非常糟糕的主意.这是因为终止线程不知道目标正在做什么以及它是否处于"安全"终止点.例如,您可能正在编写输出,进行计算或其他任何操作.

相反,你应该向另一个线程发送一个信号(使用多种方法中的任何一个),并且该线程退出自己.退出线程只需从线程的run方法返回.