The so-called background thread refersProgramA General Service thread is provided in the background during running, and this thread is not an indispensable part of the program. Therefore, when all non-Background threads end, the program will terminate and all background threads will be killed. Conversely, the program will not be terminated as long as any non-Background thread (User thread) is still running.The background thread terminates the run method without executing the finally clause..The subthread created by the background thread is also a background thread.
The following is an example of a background thread:
Package demo. thread; import Java. util. concurrent. timeunit; public class daemondemo implements runnable {@ overridepublic void run () {try {While (true) {thread. sleep (1, 1000); system. out. println ("#" + thread. currentthread (). getname () ;}} catch (interruptedexception e) {e. printstacktrace ();} finally {// The background thread does not execute the finally Clause system. out. println ("finally") ;}} public static void main (string [] ARGs) {for (INT I = 0; I <10; I ++) {thread daemon = new thread (New daemondemo (); // It must be set to the background thread daemon before start. setdaemon (true); daemon. start ();} system. out. println ("all daemons started"); try {timeunit. milliseconds. sleep (1000);} catch (interruptedexception e) {// todo auto-generated catch blocke. printstacktrace ();}}}
Running result:
All daemons started
# Thread-2
# Thread-3
# Thread-1
# Thread-0
# Thread-9
# Thread-6
# Thread-8
# Thread-5
# Thread-7
# Thread-4
Analysis: From the results, we can see that the ten sub-threads do not print wireless loops. Instead, after the main thread (main () exits, the JVM forces to close all background threads. There is no desired confirmation form, for example, the finally clause is not executed.