There are two types of threads in Java, one for the user thread and one for the daemon thread.
A daemon thread is a special thread that has the meaning of "companionship", which is automatically destroyed when there is no non-daemon thread in the process.
A typical daemon thread is a garbage collection thread.
When there are no threads in the process, there is no need for the garbage collection thread to exist and is automatically destroyed.
Any daemon thread is the nanny of all the non-daemon threads in the JVM, as long as any non-daemon thread exists in the current JVM instance and does not end, the daemon is working, and when the last non-daemon thread ends, the guard line friend with the JVM.
Daemon's role is to facilitate the operation of other threads, the most typical application of the daemon is the GC.
Thread Code:
Public classThread1extendsThread {Private inti = 0; @Override Public voidrun () {Try { while(true) {i++; System.out.println ("I =" +i); Thread.Sleep (1000); } } Catch(interruptedexception e) {e.printstacktrace (); } }}
Execute code:
Public classMain { Public Static voidMain (string[] args) {Try{Thread1 thread=NewThread1 (); Thread.setdaemon (true); Thread.Start (); Thread.Sleep (5000); System.out.println ("The main thread has stopped, and the daemon thread has stopped. Not in print. "); } Catch(interruptedexception e) {e.printstacktrace (); } }}
Execution Result:
As the main thread stops working, the daemon thread also stops working.
1.11 Daemon Threads