一.守护线程
1.守护线程示例
package com.miracle.concurrency.chapter4;
public class DaemonThread {
public static void main(String[] args) {
Thread t = new Thread(){
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " running");
// 这里子线程,sleep100秒
Thread.sleep(100_000);
System.out.println(Thread.currentThread().getName() + " done");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();
try {
// 这里主线程,sleep10秒
Thread.sleep(10_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
执行代码发现主线程休眠10秒后退出结束,然而子线程还在运行,jvm还未退出
package com.miracle.concurrency.chapter4;
public class DaemonThread {
public static void main(String[] args) {
Thread t = new Thread(){
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " running");
Thread.sleep(100_000);
System.out.println(Thread.currentThread().getName() + " done");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
// 设置线程t为main的守护线程
t.setDaemon(true);
t.start();
try {
Thread.sleep(10_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
执行代码发现主线程休眠10秒后退出结束,同时子线程并未执行完毕就退出了,jvm关闭