//守護線程:可以看成是後臺線程,依賴於前臺線程,當前臺線程全部結束時
//即使後臺線程的任務代碼沒有執行完,也會立刻結束,比如垃圾回收線程,
//就屬於守護線程
class Demo implements Runnable{
boolean flag = true;
public synchronized void run(){
while(flag){
try{
wait();
}
catch(InterruptedException e){
e.printStackTrace();
flag = false;
}
System.out.println(Thread.currentThread().getName()+"...Hello World!");
}
}
}
class test{
public static void main(String[] args){
Demo demo = new Demo();
Thread t1 = new Thread(demo);
Thread t2 = new Thread(demo);
t2.setDaemon(true);//把t2線程設置成守護線程,t1線程和主線程都結束之後
//t2也就必須結束了
t1.start();
t2.start();
try{Thread.sleep(20);}catch(InterruptedException e){e.printStackTrace();}
int i = 1;
while(true){
if(i++==500){
t1.interrupt();
//讓t2不能結束
//t2.interrupt();
break;
}
}
}
}
Java——守護線程
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.