守护线程

Java中的线程可以分为两类,即非守护线程和守护线程。

关于守护线程要注意的是:

(1)当jvm中只剩下守护线程时,JVM会退出,所以不要在守护 线程中做比较重要的操作,比如文件读写等

(2)在Daemon线程中产生的新线程也是Daemon的

(3) 守护线程结束只与JVM中是否还有非守护线程右关,而与创建守护线程的父线程是否结束有关

 

Java垃圾回收线程就是一个典型的守护线程,当JVM中没有非守护线程时JVM回退出

public class Test {

    static class DaemonRunner implements Runnable {
        @Override
        public void run() {
            while (true) {
                for (int i = 1; i <= 100; i++) {
                    System.out.println("daemon thread:" + i);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) {

        Thread daemonThread = new Thread(new DaemonRunner());
        daemonThread.setDaemon(true);
        daemonThread.start();
        System.out.println("isDaemon? = " + daemonThread.isDaemon());
        
        Scanner scanner = new Scanner(System.in);
        scanner.next();
        
    }
}

 

 关于第(3)的例子

public class Demo {

    public static void main(String[] args) {
        new Thread(()->{
            Thread th =  new Thread(
                    ()->{
                        for(int i = 1 ; i<= 100;i++) {
                            System.out.println("index = " + i);
                            try {
                                Thread.sleep(1_000);
                            } catch (InterruptedException e) {
                            }
                        }
                    }
            );
            th.setDaemon(true);
            th.start();
            
            try {
                Thread.sleep(2_000);
                System.out.println("out thread is over ");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        
        new Thread(()-> {
            try {
                Thread.sleep(5_000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

 

posted @ 2019-04-13 23:17  踏月而来  阅读(238)  评论(0编辑  收藏  举报