public class Test { public static void main(String[] args) throws InterruptedException { DaemonThread daemon = new DaemonThread(); daemon.setDaemon(true); // 先设置守护为true,在开始线程 daemon.start(); Thread.sleep(2000); //主线程结束,守护线程跟着结束 } static class DaemonThread extends Thread { @Override public void run() { while (true) { System.out.println("i am alive"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }