I. Overview
A daemon thread is a special kind of thread whose particularity lies in:
[1] Depends on other non-daemon threads. Once there are no other types of threads running in the whole program, the daemon thread is automatically terminated.
[2] The priority level of operation is low, and some system-level auxiliary behaviors can be performed.
2. Create a daemon thread.
In fact, creating a daemon thread is no different from a general thread, except that the thread needs to be set as a daemon thread before the thread starts.
example:
Thread thread = new Thread() { @Override public void run() { for(;;) System.out.println(" I am is a daemon Thread ..."); } }; thread.setDaemon(true); thread.start(); Thread.sleep(3000); System.out.println("end ....");
To create a daemon thread, you only need to pay attention to setting a daemon property.
3. Operation results
We run the above code and find that the daemon thread automatically terminates itself after 3 seconds.
This is a feature of daemon threads. When there is no non-daemon thread running in the runtime environment, the daemon thread automatically terminates itself.