Daemon thread life cycle: A daemon is a special thread running in the background,
It is independent of the control terminal and performs certain tasks periodically or waits for certain occurrences to be handled.
That is, the daemon thread does not depend on the terminal, but relies on the system, "die" with the system.
When all the threads in the JVM are daemons, the JVM can exit, and if there is one or more non-daemons, the JVM will not exit.
Public classGrammerTest3 { Public Static voidMain (String ... args) {Thread T1=NewMyUser (); Thread T2=NewMydaemon (); T2.setdaemon (true); T1.start (); T2.start (); System.out.println ("The main thread is finished."); }}/** User Process*/classMyUserextendsthread{ Public voidrun () { for(inti=0; i< 5; i++) {System.out.println ("User thread Thread111111111 i==" +i); Try{Thread.Sleep (100); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }} System.out.println ("User thread Thread111111111 Run End"); }}classMydaemonextendsthread{ Public voidrun () { for(inti=0; i< 99; i++) {System.out.println ("Daemon Thread i==" +i); Try{Thread.Sleep (100); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }} System.out.println ("Daemon Thread Run End"); }}
Operation Result:
Main thread ends Daemon thread i==0 user thread Thread111111111 i==0 user thread Thread111111111 i==1 daemon thread i==1 User thread Thread111111111 i==2 daemon thread i==2 user thread Thread111111111 i==3 daemon thread i==3 User thread Thread111111111 i==4 daemon thread i==4 user thread Thread111111111 run end daemon I==5
(Run end)
This means that when the user thread exits, it exits even if the daemon thread is not finished.
Java Daemon Thread