Daemon Threads in Java

Source: Internet
Author: User

Winded

There are two types of threads in Java: User thread, Daemon thread (daemon thread)

    • Definition: A daemon thread (AKA: Service thread) that automatically leaves when no user thread is available for service.
    • Priority: The daemon thread has a lower priority and is used to service other objects and threads in the system.

The user thread is the thread that is running in the foreground, and the daemon thread is the thread running in the background. That is, the daemon thread does not depend on the terminal, but relies on the system, "die" with the system. The role of the daemon is to facilitate the operation of other foreground threads, and only when the normal, non-daemon thread is still running, such as a garbage collection thread is a daemon thread, when there is no longer any thread running in our program, the program will not generate garbage, the garbage collector will have nothing to do, So when the garbage collection thread is the only thread remaining on the JVM, the garbage collection thread will automatically leave. It is always running in a low-level state for real-time monitoring and management of recyclable resources in the system. When the VM detects only one daemon thread, and the user thread exits the runtime, the VM exits because there is no need to continue running the program without the Guardian. If a non-daemon thread is still alive, the VM will not exit.

The daemon thread is not only available inside the virtual machine, but the user can also set the daemon itself when writing the program. The user can set the current thread as the daemon thread by using the thread's Setdaemon (True) method.

While the daemon may be useful, care must be taken to ensure that all other non-daemon threads die without any harm from its termination. Because you cannot know whether the daemon has completed the expected service task before all the user threads are out of operation. Once all the user threads have exited, the virtual machine exits and runs. Therefore, do not perform business logic operations (such as reading and writing data) in the daemon thread.

Chestnuts??
 Packagezhengbin.test;ImportJava.util.Scanner;/*** Created by zhengbin06 on 2016/10/18.*/ Public classDaemonrunnerImplementsrunnable{@Override Public voidrun () { while(true) {             for(inti = 1;i <= 100;i++) {System.out.println (i); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }            }        }    }     Public Static voidMain (string[] args) {Thread daemonthread=NewThread (NewDaemonrunner ()); //Set as daemon thread        /*** Mark the thread as either a daemon thread or a user thread.         When a running thread is a daemon thread, the Java virtual machine exits.         * The method must be called before the thread is started. * The method first calls the thread CheckAccess method without any parameters.         This may throw SecurityException (in the current thread). */Daemonthread.setdaemon (true); //executing the daemon threadDaemonthread.start (); //Isdaemon () tests whether the thread is a daemon thread. System.out.println ("Isdaemon =" +Daemonthread.isdaemon ()); Scanner Scanner=NewScanner (system.in); //accept the input so that the program pauses and once the user input is accepted, the main thread ends and the JVM exits!Scanner.next (); //The Addshutdownhook method increases the processing event to be handled when the JVM stops://when the JVM exits, the JVM Exit statement is printed. Runtime.getruntime (). Addshutdownhook (NewThread () {/*** GetRuntime () returns the run-time object associated with the current Java application.             Most methods of the runtime class are instance methods, and must be called according to the current run-time object.             * Addshutdownhook () register a new virtual machine to close the hook. */@Override Public voidrun () {System.out.println ("JVM exit!");    }        }); }}

Above the pest, the first to open a daemon thread, increment output per second printing, while the main line measuring modules (blocking) scanner, when the console input information, the main thread ends, there is no non-daemon thread exists, the daemon thread terminates, stop the output, the program terminates.

The PID of all current processes is obtained by JPS, and all threads in the process are viewed through jstack, based on the PID:

It can be observed that a "main", a "Thread-0".

Daemon Threads in Java

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.