Java threads are divided into two types: the user thread and the daemon thread. A daemon thread or process is a daemon thread or process, but the daemon thread in Java is a bit different from the daemon in Linux.
The daemon process in Linux actually refers to the process of running a service in the background, such as the crond of the Cron service, the httpd that provides the HTTP service, and the daemon thread in Java, which means that only daemon is left in the JVM instance, and the JVM exits.
We look at the differences between daemon threads and normal user threads through the following experiments
- Creates a daemon thread that runs a dead loop, exits after the main thread runs 5s, and the daemon thread exits.
Public Static void Main(string[] args)throwsinterruptedexception {Thread thread =NewThread (New MyThread()); Thread.Setdaemon(true);//Set thread to daemon threadThread.Start(); Thread.Sleep( the);//5s after the main thread exits}Static classMyThreadImplementsRunnable {@Override Public void Run() { while(true) {//thread dead loop Try{//100ms printing once HelloThread.Sleep( -); }Catch(Interruptedexception e) {e.Printstacktrace(); } System. out.println("Hello"); } } }
Run Result: 5ms daemon thread exits.
hellohellohellohellohellohellohellohellohellohellohelloProcess finished with exit code 0
Comment out the daemon so that the thread becomes a normal user thread
Public Static void Main(string[] args)throwsinterruptedexception {Thread thread =NewThread (New MyThread());//Thread.setdaemon (TRUE);//normal user threadThread.Start(); Thread.Sleep( the);//5s after the main thread exits}Static classMyThreadImplementsRunnable {@Override Public void Run() { while(true) {//thread dead loop Try{//100ms printing once HelloThread.Sleep( -); }Catch(Interruptedexception e) {e.Printstacktrace(); } System. out.println("Hello"); } }}
Run Result: The thread will not exit after the main course is run, it is always dead loop
JAVA Daemon Thread Understanding