JAVA DAEMON线程的理解

java线程分两种:用户线程和daemon线程。daemon线程或进程就是守护线程或者进程,但是java中所说的daemon线程和linux中的daemon是有一点区别的。

linux中的daemon进程实际是指运行在后台提供某种服务的进程,例如cron服务的crond、提供http服务的httpd;而java中的daemon线程是指jvm实例中只剩下daemon的时候,jvm就会退出。

我们通过以下实验来看下daemon线程和普通用户线程的区别

  1. 创建一个运行死循环的daemon线程,主线程运行5s后退出,daemon线程也会退出。
public static void main(String[] args) throws InterruptedException {

        Thread thread = new Thread(new MyThread());
        thread.setDaemon(true); // 设置线程为daemon线程
        thread.start();

        Thread.sleep(5000); // 5s后主线程退出
    }


    static class MyThread implements Runnable {

        @Override
        public void run() {
            while (true) { // 线程死循环
                try {
                    // 100ms 打印一次hello
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("hello");
            }
        }
    }

运行结果:5ms daemon线程退出。

hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello

Process finished with exit code 0
  1. 注释掉daemon,使得线程成为一个普通的用户线程
public static void main(String[] args) throws InterruptedException {

        Thread thread = new Thread(new MyThread());
        // thread.setDaemon(true); // 普通的用户线程
        thread.start();

        Thread.sleep(5000); // 5s后主线程退出
    }


    static class MyThread implements Runnable {

        @Override
        public void run() {
            while (true) { // 线程死循环
                try {
                    // 100ms 打印一次hello
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("hello");
            }
        }
    }

运行结果:线程在主线程运行完后不会退出,一直死循环

原文地址:https://www.cnblogs.com/set-cookie/p/8728224.html