一、在start以前,setDaemon。 該現場就成爲守護線程了。ide
二、守護現線程並非主線程結束,子線程(守護線程)也跟着結束。而是守護線程在沒有用戶線程運行的狀況伴隨着JVM退出而結束。線程
示例代碼:io
public class Demo {class
public static void main(String[] args) {thread
//守護現線程並非主線程結束,子線程(守護線程)也跟着結束。而是守護線程在沒有用戶線程運行的狀況伴隨着JVM退出而結束。程序
MyMainThread my=new MyMainThread();im
Thread thread=new Thread(my);static
thread.start();di
for(int i=0;i<20;i++) {while
System.out.println("我是主程序,我依舊堅挺");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO 自動生成的 catch 塊
e.printStackTrace();
} }
} }
//主線程
class MyMainThread implements Runnable{
@Override public void run() {
MyThread my=new MyThread();
Thread tt=new Thread(my);
tt.setDaemon(true); //設置爲守護線程 tt.start();
for(int i=0;i<10;i++) {
System.out.println("我是主線程。。。。。。。。。");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO 自動生成的 catch 塊
e.printStackTrace();
}
}
}
}
//子線程(守護線程)
class MyThread implements Runnable{
@Override public void run() {
while(true) {
System.out.println("我是子線程,我正在運行-----------------------------");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO 自動生成的 catch 塊
e.printStackTrace();
}
}
}
}