java:为什么主线程等待子线程完成

标签 java multithreading

我有一个简单的java程序。创建一个主线程 (main()) 并启动另一个线程 t

class T extends Thread{
    @Override
    public void run() {
        while (true){
            System.out.println("Inside thread");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Thread t = new T();
        t.start();
        //t.join();
        System.out.println("end");
    }
}

输出:
end
Inside thread
Inside thread
Inside thread
....
....

它无限打印 内部线程 。我不是在使用 join() 等待主线程中的子线程。打印 end 后主线程不应该退出吗?

更新:

When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:

  • The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
  • All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.


我找到了原因。第二点澄清了它。我假设所有子线程都将在主线程退出后终止(我错了)并且 JVM 应该关闭。

最佳答案

主线程已经退出。这是另一个还活着的线程。

关于java:为什么主线程等待子线程完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42515650/

相关文章:

java - Android:存储在 SQLite 中时图像的字节数组为空

java - 创建直方图

java - Java 条件等待和通知

multithreading - IIS Web花园是否使用线程或进程?

java - 如何到达第一个Java线程0?

c# - Silverlight 和非 UI 线程中的回调

java - 无法解析java中的 optional

java - 为什么我的阵列从我正在阅读的文件中删除零?

c++ - MingW 中的多线程 Windows 服务

java - Spring java配置EJB代理不工作