1.11 Daemon Threads

Source: Internet
Author: User

There are two types of threads in Java, one for the user thread and one for the daemon thread.

A daemon thread is a special thread that has the meaning of "companionship", which is automatically destroyed when there is no non-daemon thread in the process.

A typical daemon thread is a garbage collection thread.

When there are no threads in the process, there is no need for the garbage collection thread to exist and is automatically destroyed.

Any daemon thread is the nanny of all the non-daemon threads in the JVM, as long as any non-daemon thread exists in the current JVM instance and does not end, the daemon is working, and when the last non-daemon thread ends, the guard line friend with the JVM.

Daemon's role is to facilitate the operation of other threads, the most typical application of the daemon is the GC.

Thread Code:

 Public classThread1extendsThread {Private inti = 0; @Override Public voidrun () {Try {             while(true) {i++; System.out.println ("I =" +i); Thread.Sleep (1000); }        } Catch(interruptedexception e) {e.printstacktrace (); }    }}

Execute code:

 Public classMain { Public Static voidMain (string[] args) {Try{Thread1 thread=NewThread1 (); Thread.setdaemon (true);            Thread.Start (); Thread.Sleep (5000); System.out.println ("The main thread has stopped, and the daemon thread has stopped. Not in print. "); } Catch(interruptedexception e) {e.printstacktrace (); }    }}

Execution Result:

As the main thread stops working, the daemon thread also stops working.

1.11 Daemon Threads

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.