java:为什么主线程等待子线程完成 [英] java: why main thread waits for child thread to finish

查看:63
本文介绍了java:为什么主线程等待子线程完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple java program. A main thread (main()) is created and starts another thread 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() 等待主线程中的子线程.打印结束后主线程不应该退出吗?

It infinitely prints Inside thread. I am not waiting for child thread in main thread using join(). Shouldn't main thread exit after printing end?

更新:

Java 虚拟机启动时,通常只有一个非守护线程(通常调用一些名为 main 的方法)指定班级).Java 虚拟机继续执行线程,直到发生以下任一情况:

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:

  • 已调用 Runtime 类的退出方法,并且安全管理器已允许退出操作发生.
  • 所有不是守护线程的线程都已死亡,无论是从对 run 方法的调用返回还是通过抛出异常传播到 run 方法之外.

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

I found the reason. The second point clarified it. I was in assumption that all child thread will terminates after main thread exits (I was wrong) and JVM should shutdown.

推荐答案

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

The main thread has exited. It's the other thread that's still alive.

这篇关于java:为什么主线程等待子线程完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆