Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
547 views
in Technique[技术] by (71.8m points)

multithreading - java daemon thread and non-daemon thread

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. When an application begins running, there is one daemon thread, whose job is to execute main().

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

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

This is incorrect. See below.

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

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. A thread created by a daemon thread is initially also a daemon thread.

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

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...