2.5 驻守后台:守护线程

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 会抛异常
*/
}
}
原文地址:https://www.cnblogs.com/anxbb/p/8425435.html