为什么一个线程比Java中的main方法更长? [英] Why does a thread outlive the main method in Java?

查看:126
本文介绍了为什么一个线程比Java中的main方法更长?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在教自己Java线程,我注意到一些让我困惑的东西。我创建了一个名为 engine 的类,实现 Runnable 。 run方法只打印Hello World,休眠一秒,然后重复。

I was teaching myself Java threading and I noticed something that confuses me a little. I made a class called engine implementing Runnable. The run method just prints "Hello World", sleeps for a second, and repeats.

在我的main方法中,我有:

In my main method, I have:

public static void main(String[] args) {
    Thread thread = new Thread(engine);
    thread.start();
    System.out.println("Done.");
}

正如我所料,我看到Hello World和Done。快速印刷,意味着主要方法已经到了最后,但我没想到的是,即使在主要结束之后,我开始运行的线程也一直在运行。

As I expected, I see "Hello World" and "Done." printed quickly, meaning the main method has reached the end, but what I didn't expect was that the thread I started kept running even after the end of main was reached.

为什么程序在主要出口后仍继​​续执行?我会想到,当主要退出时,进程将终止并且所有线程都将被强制清除。这是否意味着必须为每个Java程序显式连接/终止每个线程?

Why does the program continue to execute even after main exits? I would have thought that when main exited the process would terminate and all of the threads would be cleaned up forcefully. Does this mean that every thread has to be joined/killed explicitly for a Java program to terminate?

推荐答案

如果你想要你的程序在main方法完成时退出,考虑制作你的线程守护进程。但是请注意这样一个事实,当主要完成时,守护程序线程将被中止。

您可以像这样创建一个守护进程:

If you want your program to exit when the main method finished, consider making your threads daemons. But take care of the fact, that daemon threads will be aborted, when main finishes.
You can create a daemon thead like so:

Thread t = new Thread(...);
t.setDaemon(true);

所有非守护程序线程都是用户线程。那些线程正在阻止jvm关闭。

All non-daemon threads are user threads. Those threads are stopping the jvm from closing.

这篇关于为什么一个线程比Java中的main方法更长?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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