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