1. 程式人生 > >2.5 駐守後臺:守護線程

2.5 駐守後臺:守護線程

setname sta main rac cat nal boolean string check

package 第二章.守護線程;

/**
* Created by zzq on 2018/1/18.
*/
public class 守護線程Test {
public static class MyThread extends Thread{
private int i = 0;
@Override
public void run(){
super.run();
try{
while(true){
i++;
System.out.println("i="+i);
Thread.sleep(1000);
}
}catch(InterruptedException ie){
ie.printStackTrace();
}
}
}
public static class testThread extends Thread{
@Override
public void run(){
try{
Thread.sleep(10000); //testThread線程約10秒後結束
System.out.println(Thread.currentThread().getName()+"線程結束!");
}catch(InterruptedException ie){
ie.printStackTrace();
}
}
}
public static class T1 extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i);
}
}
}

public static void main(String[] args) throws InterruptedException {
try{
MyThread thread = new MyThread();
thread.setName("thread");
thread.setDaemon(true); //將thread線程設為守護線程
thread.start();
testThread t = new testThread();
t.setName("testThread");
t.start();
t.stop();
Thread.sleep(5000);//main線程在這裏停留5秒
System.out.println("主線程結束了");//5秒後main線程結束了,但是testThread線程還在執行,所以守護線程繼續工作

/*當所有線程都結束時,thread線程也隨之結束*/
}catch(InterruptedException ie){
ie.printStackTrace();
}
/*守護線程 必須在start()方法之前 不然會報錯,告訴你設置守護線程失敗
public final void setDaemon(boolean on) {
checkAccess();
if (isAlive()) {
throw new IllegalThreadStateException();
}
daemon = on;
}
源碼中說明 如果線程的運行狀態是true 會拋異常
*/
}
}

2.5 駐守後臺:守護線程