(Java多线程系列五)守护线程

守护线程

什么是守护线程

Java中有两种线程,一种是用户线程,一种是守护线程。

当进程不存在或主线程停止,守护线程也会自动停止。

class DaemonThread extends Thread {
    @Override
    public void run() {
        while (true) {
            System.out.println("我是守护线程。。。只要守护的线程不挂,我永远都不挂");
        }
    }
}

public class DaemonThreadDemo {

    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                DaemonThread daemonThread = new DaemonThread();
                daemonThread.setDaemon(true);
                daemonThread.start();
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("主线程运行完成退出。。。");
            }
        });

        thread.start();
    }

}

Image 守护线程

源码地址

猜你喜欢

转载自www.cnblogs.com/3LittleStones/p/12090629.html