Java daemon-meaningless

Source: Internet
Author: User

What is the Java daemon thread?

Isn't it a thread setdaemon (true?

Generally, developers know this, but do they know how it works? What is the difference between it and the user thread ???

This may not be clear, and I have always felt quite clear about it. Recently I found it unclear.

Haha

Next, let's summarize what the daemon thread is doing.

First, let's look at what the daemon thread is doing, and then let's talk about what the Java daemon thread is doing.

Take the Linux daemon as an example to see how the daemon works.

Look at the definition: daemon is a special process running in the background. It is independent of the control terminal and periodically executes a task or waits to process some events.

That is to say, the daemon thread does not depend on the terminal, but on the system. It is "same to the system ".

What does the Java daemon look like.

When all threads in the JVM are daemon threads, the JVM can exit;

If there is one or more non-daemon threads, they will not exit.

So the only significance of setdeamon (true) is to tell JVM that it does not need to wait for the thread to run to end (exit). When JVM wants to exit, it can exit.

Needless to say, it is useless:

Let's look at the example.

Public class deamonthread extends thread {
Public void run (){
Try {
For (INT I = 0; I <10; I ++ ){
Thread. Sleep (1000 );
System. Out. println (I );
}
}
Catch (exception e ){
E. printstacktrace ();
}
}
Public static void main (string [] ARGs ){
Thread thread = new deamonthread ();
Thread. setdaemon (true );
Thread. Start ();
}
}

What information will this program print ??

Number ???

If we set

Thread. setdaemon (true );

Then, the number can be printed.

So what does he print?

The result is not printed.

This is the daemon thread, guarding the last user thread. If there is no user thread, it will not work. Do not quit ??

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.