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

标签 java multithreading

我在 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();    
}

最佳答案

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

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

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

这是一个简单的小代码片段,用于说明差异。在 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) {}
        }
    }
}

关于java - 如何在另一个线程仍在运行时停止主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23240643/

相关文章:

另一个窗口中的 Java 窗口

java - Hadoop上的支持 vector 机

C++11增加原子变量,赋值给其他值,是原子操作吗?

java - Singleton 类中的非静态成员

python - 多个程序可以同时写入 STDOUT 吗?

java - 如何很好地指定/组织/清理项目中的jar库

java - 如何将 int 转换/转换为对象? (java)

java - 尝试用随机数创建 for 循环?

java - 子线程如何通知父线程终止所有其他子线程java

multithreading - Tomcat 停止工作 : there are no ajp available