java守护线程

守护线程: 运行在后台为其他前台线程服务
特点:随着所有的用户线程的结束 守护线程会随着用户线程一起结束
应用:数据库连接池中的监测线程
Java虚拟机启动后的监测线程
最常见的守护线程 垃圾回收线程
如果设置成守护线程呢?
可以调用线程类Thread setDaemon(true) 方法来设置当前的线程为守护线程
设置守护线程注意事项
setDaemon(true)必须在start 之前调用否则会抛出IllegalThreadStateException
在守护线程中产生的新线程也是守护线程
不是所有的线程都可以分配给守护线程来执行 如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());
}
}

你可能感兴趣的:(java守护线程)