例子如下:
public class DemoThread { public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new Runnable() { @Override public void run() { while (true){ System.out.println("hello daemon thread"); } } }); thread.setDaemon(true); //这一行去掉之后,JVM会一直运行,守护线程会随着主线程死亡而死亡 thread.start(); Thread.sleep(3000); } }