守護線程: 運行在后臺為其他前臺線程服務
特點:隨著所有的用戶線程的結束 守護線程會隨著用戶線程一起結束
應用:數據庫連接池中的監(jiān)測線程
Java虛擬機啟動后的監(jiān)測線程
最常見的守護線程 垃圾回收線程
如果設置成守護線程呢?
可以調用線程類Thread setDaemon(true) 方法來設置當前的線程為守護線程
設置守護線程注意事項
setDaemon(true)必須在start 之前調用否則會拋出IllegalThreadStateException
在守護線程中產生的新線程也是守護線程
不是所有的線程都可以分配給守護線程來執(zhí)行 如io操作和計算
守護線程示例代碼:
class DaemonThread implements Runnable{
@Override
public void run() {
System.out.println("進入守護線程"+Thread.currentThread().getName());
try {
writeToFile();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("退出守護線程"+Thread.currentThread().getName());
}
private void writeToFile() throws Exception {
File filename = new File("/Users/thl"
+File.separator+"daemon.txt");
OutputStream os = new FileOutputStream(filename,true);
int count = 0;
while (count< 999){
os.write(("\r\nword"+count).getBytes());
System.out.println("守護線程"+Thread.currentThread().getName()
+"向文件中寫入了word"+count++);
Thread.sleep(1000);
}
}
}
public class DaemonThreadDemo {
public static void main(String[] args){
System.out.println("進入主線程"+Thread.currentThread().getName());
DaemonThread daemonThread = new DaemonThread();
Thread thread = new Thread(daemonThread);
thread.setDaemon(true);
thread.start();
Scanner sc = new Scanner(System.in);
sc.next();
System.out.println("退出主線程"+Thread.currentThread().getName());
}
}