美文网首页
Thread 之守护线程

Thread 之守护线程

作者: 案玉璃青 | 来源:发表于2020-10-09 16:49 被阅读0次

先来看看下面这个例子:

class Test extends Thread {

        @Override public void run() {

                setName("thread");

                try {

                        sleep(200);

                } catch (InterruptedException e) {

                        e.printStackTrace();

                }

                System.out.println(Thread.currentThread().getName());

        }

        public static void main(String[] args) {

                Thread thread = new Test();

                thread.setDaemon(true); // 设置为守护线程

                thread.run();

                thread.start();

        }

}

结果是只打印 main:

结果

这是因为当所有常规线程运行完毕以后,守护线程不管运行到哪里,虚拟机都会退出运行。

通过 thread 实例调用 run 方法的行为是在 main 中进行的,这里为主线程,所以打印 main;之后调用 start 方法启动线程执行 run 时,main 已经执行完毕,而该线程为守护线程,虚拟机不必等待线程执行完就已经退出了,所以不会打印 thread。

相关文章

网友评论

      本文标题:Thread 之守护线程

      本文链接:https://www.haomeiwen.com/subject/bnglpktx.html