【问题标题】:how to stop main thread while another thread still running如何在另一个线程仍在运行时停止主线程
【发布时间】:2016-04-13 22:19:40
【问题描述】:

我在 main 方法中启动了 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();    
}

【问题讨论】:

  • System.exit(0); 将停止整个应用程序,那么您怎么知道,您的线程 t1 仍在运行?
  • 是的,我知道这种方法将决定应用程序。但我只想停止主线程。这不可能吗?

标签: java multithreading


【解决方案1】:

当 Java 程序启动时,一个线程立即开始运行。这通常称为程序的 ma​​in 线程,因为它是在程序开始时执行的线程。主线程之所以重要有两个原因:

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

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

这里有一个简单的小代码sn-p,来说明区别。用 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) {}
        }
    }
}

【讨论】:

    【解决方案2】:

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

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

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

    比较this questionanswer to another similar questiondocumentation

    【讨论】:

    • tnx 为您解答,我用两个 t1 线程测试我的问题并在 t1 中定义 t2 然后停止 t1 并看到 t2 仍在运行,但我想了解主线程
    • 所以从你的回答中我明白了 t1.start();只是 t1 线程正在运行,我认为主线程刚刚结束 System.exit();
    • 不,System.exit() 明确终止整个虚拟机。到达其代码路径末尾的线程只需从该 VM 的活动线程集中删除,然后该 VM 将检查其他非守护线程是否仍在运行。如果不是,它将自行终止。如果是,它将继续运行。 System.exit() 根本不涉及,除非(由您)明确调用:)
    【解决方案3】:

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

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

    【讨论】:

    • 我相信 Thread.join() 会强制主线程等待所有其他线程完成执行。在这种情况下,他似乎在子线程仍在运行时停止了主线程。如果这是他的情况, Thread.join() 将无济于事。
    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-22
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多