守护线程是服务于用户线程或主线程的的,当用户线程或主线程结束时,守护线程自然结束。 jvm 垃圾回收期就是一个守护线程。
setDaemon(boolean on) on为true是设置为守护线程
下面是一个列子:
package com.test;
public class B extends Thread {
public static void main(String[] args) {
Thread t1 = new MyCommon();
Thread t2 = new Thread(new MyDaemon());
t2.setDaemon(true); // 设置为守护线程
t2.start();
t1.start(); } }
class MyCommon extends Thread { public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("线程1第" + i + "次执行!");
try {
Thread.sleep(7); }
catch (InterruptedException e) {
e.printStackTrace(); } }
} }
class MyDaemon implements Runnable {
public void run() {
for (long i = 0; i < 9999999L; i++) {
System.out.println("后台线程第" + i + "次执行!"); try {
Thread.sleep(7); } catch (
InterruptedException e) {
e.printStackTrace();
}
}
}
}