Java 如何在另一个线程仍在运行时停止主线程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23240643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:28:26  来源:igfitidea点击:

how to stop main thread while another thread still running

javamultithreading

提问by Ahmad Vatani

I started t1 thread in my main method and want to stop main thread but my t1 thread still running. It is possible? how?

我在主方法中启动了 t1 线程并想停止主线程但我的 t1 线程仍在运行。有可能的?如何?

public static void main(String[] args) 
{
    Thread t1=new Thread()
    {
      public void run()
      {
          while(true)
          {
              try
              {
                  Thread.sleep(2000);
                  System.out.println("thread 1");

              }
              catch(Exception e)
              {}
          }             
      }
    };

    t1.start();    
}

采纳答案by hiergiltdiestfu

Regular Threads can prevent the VM from terminating normally (i.e. by reaching the end of the main method - you are notusing System#exit() in your example, which will terminate the VM as per documentation).

常规线程可以阻止 VM 正常终止(即通过到达 main 方法的末尾 - 您在示例中没有使用 System#exit() ,这将根据文档终止 VM)。

For a thread to not prevent a regular VM termination, it must be declared a daemon thread via Thread#setDaemon(boolean) before starting the thread.

对于不阻止常规 VM 终止的线程,必须在启动线程之前通过 Thread#setDaemon(boolean) 将其声明为守护线程。

In your example - the main thread dies when it reaches the end of it code (after t1.start();), and the VM - including t1- dies when t1 reaches the end of its code (after the while(true) aka never or when abnormally terminating.)

在您的示例中 - 主线程在到达代码末尾(在 t1.start(); 之后)时死亡,而虚拟机 - 包括 t1- 在 t1 到达其代码末尾时(在 while(true) 之后)死亡从不或异常终止时。)

Compare this question, this answer to another similar questionand the documentation.

比较this question,this answer to another similar question文档

回答by Aryan

System.exit(0)exits the the current program.

System.exit(0)退出当前程序。

"Thread.join()" method my help you to achieve what you wanted.

Thread.join()“方法我帮你实现你想要的。

回答by aashish

When a Java program starts up, one thread begins running immediately. This is usually called the mainthread of your program, because it is the one that is executed when your program begins. The main thread is important for two reasons:

当 Java 程序启动时,一个线程立即开始运行。这通常称为程序的线程,因为它是在程序开始时执行的线程。主线程很重要,原因有二:

? It is the thread from which other "child" threads will be spawned.
? It must be the last thread to finish execution. When the main thread stops, your program terminates.

? 它是从中产生其他“”线程的线程。
? 它必须是完成执行的最后一个线程。当主线程停止时,您的程序终止。

One more thing, program terminates when all non-daemon threads die (daemon thread is a thread marked with setDaemon(true)).

还有一件事,当所有非守护线程死亡时程序终止(守护线程是一个用 setDaemon(true) 标记的线程)。

Here's a simple little code snippet, to illustrate the difference. Try it with each of the values of true and false in setDaemon.

这是一个简单的小代码片段,以说明差异。尝试使用 setDaemon 中的每个 true 和 false 值。

public class DaemonTest {
    public static void main(String[] args) {
        new WorkerThread().start();
        try {
            Thread.sleep(7500);
        } catch (InterruptedException e) {}
        System.out.println("Main Thread ending") ;
    }
}

public class WorkerThread extends Thread {
    public WorkerThread() {
        setDaemon(false) ;   // When false, (i.e. when it's a user thread),
                // the Worker thread continues to run.
                // When true, (i.e. when it's a daemon thread),
                // the Worker thread terminates when the main 
                // thread terminates.
    }

    public void run() {
        int count=0 ;
        while (true) {
            System.out.println("Hello from Worker "+count++) ;
            try {
                sleep(5000);
            } catch (InterruptedException e) {}
        }
    }
}

回答by Shikhar

You can not stop the main thread while any other thread are running. (All the child threads born out of main thread.) You can use function Thread.join() to keep the main thread waiting while other thread(s) execute.

当任何其他线程正在运行时,您不能停止主线程。(所有从主线程产生的子线程。)您可以使用函数 Thread.join() 在其他线程执行时保持主线程等待。