线程未设置daemon导致shutdown无法及时退出

来源:互联网 发布:c语言http下载文件 编辑:程序博客网 时间:2024/06/01 10:20

     某次停止tomcat后,使用jps查看进程依然存在;直接jstack查看目前后台的哪些进程还在运行,发现main线程已经没有了,说明main线程已经执行完毕,我们自己的线程依旧存在,如:CONFIG-WATCHER。

     那在什么情况下,会主线程运行完了,虚拟机还没退出呢?
参考 https://stackoverflow.com/questions/7416018/when-does-the-main-thread-stop-in-java
虚拟机会在如下两种情况下退出
1.所有的非守护线程(用户线程)执行完毕退出;
2.调用了exit方法

     如上链接里的例子其实不错的,最后加个exit,分别注释和不注释可以看到不同的运行效果,看到的同学可以自己试一下

    public static void main(String args[])    {        System.out.println("Main thread started");        new Thread(new Runnable()        {            @Override            public void run()            {                System.out.println("Second thread started");                try                {                    Thread.sleep(2000);                }                catch (Exception e)                {                }                System.out.println("Second thread (almost) finished");            }        }).start();        System.out.println("Main thread (almost) finished");        //System.exit(0);    }

那么我们的这一次shutdown.sh之后还在java程序运行的原因就是自己的线程没设置daemon属性为true了,修改就简单的在线程start之前thread.setDaemon(true)即可。其实对于长期的定时的线程,最好设置为daemon线程。防止程序无法完全退出的现象出现。