What is the Java daemon thread?
Isn't it a thread setdaemon (true?
Generally, developers know this, but do they know how it works? What is the difference between it and the user thread ???
This may not be clear, and I have always felt quite clear about it. Recently I found it unclear.
Haha
Next, let's summarize what the daemon thread is doing.
First, let's look at what the daemon thread is doing, and then let's talk about what the Java daemon thread is doing.
Take the Linux daemon as an example to see how the daemon works.
Look at the definition: daemon is a special process running in the background. It is independent of the control terminal and periodically executes a task or waits to process some events.
That is to say, the daemon thread does not depend on the terminal, but on the system. It is "same to the system ".
What does the Java daemon look like.
When all threads in the JVM are daemon threads, the JVM can exit;
If there is one or more non-daemon threads, they will not exit.
So the only significance of setdeamon (true) is to tell JVM that it does not need to wait for the thread to run to end (exit). When JVM wants to exit, it can exit.
Needless to say, it is useless:
Let's look at the example.
Public class deamonthread extends thread {
Public void run (){
Try {
For (INT I = 0; I <10; I ++ ){
Thread. Sleep (1000 );
System. Out. println (I );
}
}
Catch (exception e ){
E. printstacktrace ();
}
}
Public static void main (string [] ARGs ){
Thread thread = new deamonthread ();
Thread. setdaemon (true );
Thread. Start ();
}
}
What information will this program print ??
Number ???
If we set
Thread. setdaemon (true );
Then, the number can be printed.
So what does he print?
The result is not printed.
This is the daemon thread, guarding the last user thread. If there is no user thread, it will not work. Do not quit ??