Defined
There are two types of threads in Java: The user thread, and the Daemon thread.
A daemon thread is a special kind of thread that has a special meaning of "companionship", which is automatically destroyed when a non-daemon thread does not exist in the thread.
The garbage collection thread is a daemon thread, and the garbage collection thread is automatically destroyed when there are no non-daemon threads in the thread.
Therefore, the role of the daemon is for other non-daemon threads of the service, when the non-daemon thread does not exist, it is naturally not necessary to exist.
How to create
The creation process, like a normal thread, requires only the following functions to be called after creation:
setDaemon(true);
Judge
public final boolean isDaemon() { return daemon;}
You can use this function to determine whether a thread is a daemon thread.
Note the function Setdaemon (true) must be used before the start () function.
If Setdaemon (true) is thrown after start (), it throws an exception. As follows
That is, after a thread has been run, its type (daemon or not) is determined and cannot be changed.
The thread that is generated in the daemon thread is also the daemon thread;
In the init () function of Thread, you can see this sentence:
this.daemon = parent.isDaemon();
Test
Create a thread class
class PrimeThread extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName()+" begin"); try { int i = 0; while(true) { Thread.sleep(500); System.out.println("Current i = " + (i++)); } } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+" end"); }}
To create a test method
public static void main(String[] args) { PrimeThread primeThread = new PrimeThread(); primeThread.setDaemon(true); primeThread.start(); try { Thread.sleep(3000L); System.out.println("Main 函数准备结束了, 守护线程也机会停止, 不打印"); } catch (InterruptedException e) { e.printStackTrace(); }}
The results are as follows:
In the result, after the thread of the Main function ends, the primethread thread ends.