線程分爲用戶線程和守護線程。
虛擬機必須確保用戶線程執行完畢 ( main 主線程)
虛擬機不用等待守護線程執行完畢。(gc 垃圾回收線程)
在用戶線程結束後,守護線程會不在守護用戶線程。
舉個例子來說(僅僅是舉例子),上帝守護着小明,從小明出生開始,一直到小明死去,上帝會不會死呢?顯然是不會的,通過例子來說明一下:
package thread;
public class TestDaemon {
public static void main(String[] args) {
Runnable god = new God();
Runnable person = new Person();
Thread g = new Thread(god);
// 設置爲守護線程
g.setDaemon(true);
g.start();
Thread you = new Thread(person);
you.start();
}
}
class God implements Runnable{
@Override
public void run() {
while(true) {
System.out.println("上帝一直在守護着你。。。。。");
}
}
}
class Person implements Runnable{
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println("我已經生活了" + i + " 年");
}
System.out.println("Good Bye,World!");
}
}
效果圖: