类DaemonSpawn:
public class DaemonSpawn implements Runnable { @Override public void run() { while (true) { Thread.yield(); } } }主函数:
import java.util.concurrent.TimeUnit; public class Test1 { public static void main(String[] args) throws InterruptedException { Thread d = new Thread(new Daemon()); d.setDaemon(true); //必须在启动线程前调用 d.start(); System.out.println("d.isDaemon() = " + d.isDaemon() + "."); TimeUnit.SECONDS.sleep(1); } }运行结果如图:
d.isDaemon() = true. DaemonSpawn 0 started. DaemonSpawn 1 started. DaemonSpawn 2 started. DaemonSpawn 3 started. DaemonSpawn 4 started. DaemonSpawn 5 started. DaemonSpawn 6 started. DaemonSpawn 7 started. DaemonSpawn 8 started. DaemonSpawn 9 started. t[0].isDaemon() = true. t[1].isDaemon() = true. t[2].isDaemon() = true. t[3].isDaemon() = true. t[4].isDaemon() = true. t[5].isDaemon() = true. t[6].isDaemon() = true. t[7].isDaemon() = true. t[8].isDaemon() = true. t[9].isDaemon() = true. Process finished with exit code 0如果将mian函数中的TimeUnit.SECONDS.sleep(1);注释掉,看一下TimeUnit.SECONDS.sleep()的源码:
public void sleep(long timeout) throws InterruptedException { if (timeout > 0) { long ms = toMillis(timeout); int ns = excessNanos(timeout, ms); Thread.sleep(ms, ns); } }其实就是对Thread.sleep()的封装,提供了可读性更好的线程暂停操作
注释后代码运行如下:
以上结果也说明了如果用户线程全部退出了,只剩下守护线程存在了,虚拟机也就退出了。