Different definitions
User thread: The threads used in daily life are all user threads.
Daemon thread: a thread used to serve user threads, such as garbage collection threads.
Differences in functions
1. The difference between daemon threads and user threads is mainly that the Java virtual machine survives.
2. User thread: When any user thread has not ended, the Java virtual machine will not end. Daemon thread: If only the daemon thread is left and has not ended, the Java virtual machine ends.
Instance
Start the daemon thread in the main thread.
package com.thread.model.threads; /** * Hello world! * */ public class ThreadClass { public static void main( String[] args ) { Thread thread = new Thread(new Runnable() { public void run() { while(true) { try { System.out.println("守护线程心跳一次"); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); thread.setDaemon(true);//将该线程设置为守护线程 thread.start(); try { Thread.sleep(10000); Thread currentthread = Thread.currentThread(); System.out.println("主线程"+currentthread.getName()+"退出!"); } catch (InterruptedException e) { e.printStackTrace(); } } }
The above is the detailed content of What is the difference between daemon threads and user threads in Java?. For more information, please follow other related articles on the PHP Chinese website!