The guardian thread ： seeing the name of a thing one thinks of its function , It's the thread of the guardian thread ; stay JAVA Threads are divided into User threads (User Thread) And daemons (Daemon Thread) ; The guardian thread is used to guard the user thread . therefore JVM If there is no thread to guard , There is no sense of the existence of the guardian thread ; The most typical application of daemons is GC ( Garbage collector ). The daemons are not only provided within the virtual machine , Users can also set their own daemons when writing programs
One 、 Setting up the guardian thread
thus it can be seen JAVA By default, the thread created in the User Thread ;
setDaemon() Method must be in the calling thread's start() Call before method
Two 、 Features of daemons
1、 The guardian thread , In all non Guardian threads （ The user thread ） After that , The program will end ,JVM sign out , At the same time, it will kill all the guardian threads . So it means , Daemons are not suitable for accessing native resources , Such as file , database . Because it may be interrupted at any time ; The daemons end with the end of the main program , But user threads don't , Or as long as a user thread does not exit , The process doesn't end .
2、 By default , The thread created by the programmer is the user thread ; use setDaemon(true) You can set a thread as a background thread ; While using isDaemon( ) You can judge whether a thread is a foreground thread or a background thread ;main A thread is a user thread ;jvm The garbage collector is actually a guardian thread ;