The difference between a daemon thread and a non-daemon thread

Source: Internet
Author: User

Daemon and non-daemon threads

Recently looking at the multi-threaded timer chapter, found that the application of the daemon thread, the basic knowledge of Java still need to add.

Java is divided into two types of threads: User thread and Daemon thread

A daemon is a thread that provides a generic service in the background while the program is running, such as a garbage collection thread that is a competent guardian, and that thread is not an integral part of the program. Therefore, when all non-daemon threads end, the program terminates and kills all the daemon threads in the process. Conversely, the program will not terminate as long as any non-daemon threads are still running.

There is no essential difference between a daemon thread and a user thread: The only difference is the departure of the virtual machine: If the user thread is all out of operation, only the daemon thread is present, and the virtual machine exits. Because there is no guardian, the daemon will have no work to do, there is no need to continue to run the program.

Converting a thread to a daemon can be done by invoking the Setdaemon (true) method of the Thread object. There are a few things to keep in mind when using a daemon thread:

(1) Thread.setdaemon (true) must be set before Thread.Start () or run out of a illegalthreadstateexception exception. You cannot set a running regular thread as a daemon thread.

(2) The new thread generated in the daemon thread is also daemon.

(3) The daemon should never access an intrinsic resource, such as a file or a database, because it will be interrupted at any time, even in the middle of an operation.

Use:

Runnable tr=new testrunnable ();

Thread Thread=new thread (TR);

Thread.setdaemon (TRUE); Setting the daemon thread

Thread.Start (); Start of sub-process execution

The difference between a daemon thread and a non-daemon thread

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.