守护线程
什么是守护线程呢?用过Linux操作系统的童鞋对于Linux下的守护进程一定有了解,守护线程和守护进程的道理基本一致。在Java中,存在两种线程,一种是用户线程,一种是守护线程。守护线程是一种特殊的线程,他在执行的是一种后台服务,当一个系统中不存在非守护线程的时候,守护线程也会自己销毁,典型的守护线程就是JVM的垃圾回收线程。
设置守护线程很简单,下面是一个简单的例子:
public class Main {
public static void main(String[] args) throws InterruptedException {
TheThread theThread=new TheThread();
theThread.setDaemon(true);//设置守护线程
theThread.start();
Thread.sleep(5000);
System.out.println("全都退出啦");
}
public static class TheThread extends Thread{
public void run(){
int i = 0;
while (true){
i++;
System.out.println(Thread.currentThread().getId()+":"+i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
思考守护线程的概念,尝试以上实例。