Java Threads are divided into user threads (user thread) And Daemons (daemon
thread), They go through Thread Of daemon Attribute identifier :true Represents a daemon thread ,false Represents a user thread .
One Thread The initial default is user thread (daemon Default to false), establish Thread By default, it starts from the current thread " inherit "daemon attribute , see Thread.init method :
Thread parent = currentThread(); this.daemon = parent.isDaemon();
When the remaining running threads in the virtual machine are Daemons ,JVM I will quit ; As long as there is at least one user thread ,JVM You won't quit . Can be in Thread.start Previous call Thread.setDaemon Method to set thread properties ( User thread / Daemons ).
Only in Thread Set before running daemon attribute , If Thread It's already running , Reset daemon Will throw out IllegalThreadStateException abnormal , see Thread.setDaemon method :
public final void setDaemon(boolean on) { checkAccess(); if (isAlive()) { throw
new IllegalThreadStateException(); } daemon = on; }
example 1:thread Is the user thread , After the main thread ends ,thread It will continue to run
public static void main(String[] args) throws Exception { Thread thread = new
Thread(new Runnable() { @Override public void run() { while (true) { try {
Thread.sleep(1000L); System.out.println("still running."); } catch (
InterruptedException e) { e.printStackTrace(); } } } }); // Set thread as user thread thread.
setDaemon(false); thread.start(); Thread.sleep(3000L); System.out.println(
" Main thread exit "); } // output still running. still running. Main thread exit still running. still
running. still running. still running.
example 2:thread It's a guard thread , After the main thread ends ,thread It will stop immediately
public static void main(String[] args) throws Exception { Thread thread = new
Thread(new Runnable() { @Override public void run() { while (true) { try {
Thread.sleep(1000L); System.out.println("still running."); } catch (
InterruptedException e) { e.printStackTrace(); } } } }); // Set thread as guardian thread thread.
setDaemon(true); thread.start(); Thread.sleep(3000L); System.out.println(" Main thread exit "
); } // output still running. still running. Main thread exit
GC A thread is a guard thread , Keep low priority for garbage collection , Independent of system resources , When all user threads exit ,GC Threads are useless , Will exit immediately . Because if there is no user thread , It means that no garbage will continue to be generated , You don't have to GC The thread is broken .
It can be simply understood as a guard thread serving the user thread , When all user threads end , There is no need to guard threads .
Technology