先来一个不是守护线程的例子:
public class Thread1 implements Runnable {
public void run() {
for (;;) {
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
System.out.println("Thread 1 run");
}
}
public static void main(String[] args) {
System.out.println("Thread main started!");
try {
(new Thread(new Thread1())).start();
} catch (Exception e) {
}
System.out.println("Thread main ended!");
}
}
这样主线程结束了,但是启动线程Thread1这个实例还没有结束,将一直运行下去
来看一个守护线程的例子:
public class ThreadDaemon implements Runnable {
public void run() {
for (;;) {
System.out.println("Thread 1 run");
}
}
public static void main(String[] args) {
System.out.println("Thread main started!");
try {
Thread a = new Thread(new ThreadDaemon());
a.setDaemon(true);
a.start();
} catch (Exception e) {
}
System.out.println("Thread main ended!");
}
}
运行结果如下:
Thread main started!
Thread main ended!
Thread 1 run
Thread 1 run
Thread 1 run
Thread 1 run
Thread 1 run
后面就停止没有了输出了
说明那个子线程ThreadDaemon也结束了
这就是守护线程的含义:只要主线程退出了,不管守护线程死活都强制退出
public class Thread1 implements Runnable {
public void run() {
for (;;) {
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
System.out.println("Thread 1 run");
}
}
public static void main(String[] args) {
System.out.println("Thread main started!");
try {
(new Thread(new Thread1())).start();
} catch (Exception e) {
}
System.out.println("Thread main ended!");
}
}
这样主线程结束了,但是启动线程Thread1这个实例还没有结束,将一直运行下去
来看一个守护线程的例子:
public class ThreadDaemon implements Runnable {
public void run() {
for (;;) {
System.out.println("Thread 1 run");
}
}
public static void main(String[] args) {
System.out.println("Thread main started!");
try {
Thread a = new Thread(new ThreadDaemon());
a.setDaemon(true);
a.start();
} catch (Exception e) {
}
System.out.println("Thread main ended!");
}
}
运行结果如下:
Thread main started!
Thread main ended!
Thread 1 run
Thread 1 run
Thread 1 run
Thread 1 run
Thread 1 run
后面就停止没有了输出了
说明那个子线程ThreadDaemon也结束了
这就是守护线程的含义:只要主线程退出了,不管守护线程死活都强制退出