Java中有兩種線程,一種是用戶線程,另外一種是守護線程。ide
當進程不存在或主線程中止,守護線程也會被中止。線程
使用setDaemon(true)方法設置爲守護線程進程
**io
*class
* 什麼是守護線程? 守護線程 進程線程(主線程掛了) 守護線程也會被自動銷燬.thread
*exception
* @classDesc: 功能描述:(守護線程)方法
*/static
public class DaemonThread {while
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("我是子線程...");
}
}
});
thread.setDaemon(true);
thread.start();
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(100);
} catch (Exception e) {
}
System.out.println("我是主線程");
}
System.out.println("主線程執行完畢!");
}