Daemon线程:
线程:
- 用户线程
- 守护线程
守护线程是一种特殊的线程,在进程中不存在非守护线程了,则守护线程自动销毁。
public class DaemonThread extends Thread { private int i = 0; @Override public void run() { try { while (true) { i++; System.out.println("i=" + (i)); Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } } } public class ThreadRunMain { public static void main(String[] args) { testDaemonThread(); } public static void testDaemonThread() { try { DaemonThread dt = new DaemonThread(); dt.setDaemon(true); dt.start(); Thread.sleep(5000); System.out.println("Main thread disappear. Daemon thread will also disappear."); } catch (InterruptedException e) { e.printStackTrace(); } } }
运行结果: