守护(daemon)线程 线程分为用户线程和守护线程;虚拟机 必须确保用户线程执行完毕,用户线程比如main;虚拟机 不用等待守护线程执行完毕;守护线程,如后台记录操作 日志,监控内存,垃圾回收等 。 示例: package com.jiuhong.thread; // 测试守护线程 // 上帝守护子民 public class TestDaemon { public static void main(String[] args) { God god = new God(); People people = new People(); Thread thread1 = new Thread(god); thread1.setDaemon(true); // 默认是false,false表示用户线程 thread1.start(); // 守护线程启动 Thread thread2 = new Thread(people); thread2.start(); // 用户线程启动 } } // 上帝 class God implements Runnable{ @Override public void run() { while (true){ System.out.println("上帝保佑着你!"); } } } // 子民 class People implements Runnable{ @Override public void run() { System.out.println("=== hello world! ==="); for (int i = 0; i < 36500; i++) { System.out.println("每一天都开开心心地活着!"); } System.out.println("=== goodbye world! ==="); } }