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

     某次停止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线程。防止程序无法完全退出的现象出现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值