java守护程序线程和非守护程序线程 [英] java daemon thread and non-daemon thread

查看:134
本文介绍了java守护程序线程和非守护程序线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做java过去的考试试卷,我遇到了令我困惑的以下问题。

I am doing java past exam paper, and I have encounter the following question that is confusing me.


以下哪项是真正? (选择所有适用的选项。)

Which of the following are true? (Choose all that apply.)

A。当应用程序开始运行时,有一个守护程序线程,其作用是执行main()。

A. When an application begins running, there is one daemon thread, whose job is to execute main().

B.当应用程序开始运行时,有一个非守护程序线程,其作用是执行main()。

B. When an application begins running, there is one non-daemon thread, whose job is to execute main().

C.守护程序线程创建的线程最初也是一个守护程序线程。

C. A thread created by a daemon thread is initially also a daemon thread.

D.由非守护程序线程创建的线程最初也是非守护程序线程。

D. A thread created by a non-daemon thread is initially also a non-daemon thread.

关键答案是B,C,D,任何人都可以告诉我为什么B, C是对的吗?非常感谢。

The key answer is B,C,D, could anyone tell me why B,C is correct? Many thanks.

推荐答案


A。当应用程序开始运行时,有一个守护程序线程,其作用是执行main()。

A. When an application begins running, there is one daemon thread, whose job is to execute main().

这是不正确的。见下文。

This is incorrect. See below.


B.当应用程序开始运行时,有一个非守护程序线程,其作用是执行main()。

B. When an application begins running, there is one non-daemon thread, whose job is to execute main().

正确。当最后一个非守护程序线程退出时,JVM退出。如果主线程不是非守护进程,则JVM将启动,并看到没有非守护进程线程正在运行并将立即关闭。

Correct. The JVM exits when the last non-daemon thread exits. If the main thread wasn't non-daemon then the JVM would start up and see that there were no non-daemon threads running and would shutdown immediately.

因此,主线程必须是非守护进程线程。有关守护程序和非守护程序之间的不同的描述,请参阅我的答案:守护程序线程和低优先级线程之间的区别

So therefore the main thread must be a non-daemon thread. For a description of the different between daemon and non, see my answer here: Difference between a daemon thread and a low priority thread


C.守护程序线程创建的线程最初也是一个守护程序线程。

C. A thread created by a daemon thread is initially also a daemon thread.

D.由非守护程序线程创建的线程最初也是非守护程序线程。

D. A thread created by a non-daemon thread is initially also a non-daemon thread.

两者都是正确的。该线程默认从产生它的线程获取其守护进程状态。守护程序线程产生其他守护程序线程。非守护程序线程产生其他非守护程序线程。查看来自 Thread.init()的代码

Both are correct. The thread gets its daemon status from the thread that spawned it by default. Daemon threads spawn other daemon threads. Non-daemon threads spawn other non-daemon threads. Looking at the code from Thread.init():

Thread parent = currentThread();
...
this.daemon = parent.isDaemon();

如果要更改守护程序状态,则必须在启动线程之前执行此操作。

If you want to change the daemon status then you have to do so before the thread is started.

Thread thread = new Thread(...);
// thread has the daemon status of the current thread
// so we have to override it if we want to change that
thread.setDaemon(true);
// we need to set the daemon status _before_ the thread starts
thread.start();

这篇关于java守护程序线程和非守护程序线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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