The Java Virtual Machine exits only when all running threads are background threads. This means that we create a thread. If we set it to daemon, the virtual machine will exit after other tasks are completed even if it is still being executed.
Test code:
1 package org. foo. go; 2 class Go {3 public static void main (String [] args) 4 {5 Thread myThread = new Thread () {6 public void run () 7 {8 while (true) 9 {10 try {11 Thread. sleep (1000); 12} catch (InterruptedException e) {13 // TODO Auto-generated catch block14 e. printStackTrace (); 15} 16 System. out. print ("I'm alive! "); 17} 18} 19}; 20 myThread. setDaemon (true); 21 myThread. start (); 22 23} 24}
If 20th rows are commented out, the program will continue to run. If there are 20 rows, the program will soon end.
In addition, you must note thatBefore startupTo set whether it is daemon.