JVM 主线程退出,程序退出

关于JVM退出的问题,找到的资料都是
正常情况下当所有的non-deamon线程都结束时,JVM退出

但自己测试了一下,发现方法 startTest尽管创建了10个线程,但要是我取消了end.await,主线程结束,JVM就退出了,创建的线程也不会执行。

问题在于,通过日志可以了解,其实创建的子线程也是Non-daemon线程,那为什么JVM在还有Non-daemon线程时,也会推出呢?

代码如下,可以通过是否注释end.await调试

package com.unionpay.content.cache;



import java.util.concurrent.CountDownLatch;

import org.junit.Test;

import net.sf.ehcache.Element;

public class EhcacheTest {
    CountDownLatch start;
    CountDownLatch end;
    int threadsNum=10;
    int startThead=3;

    @Test
    public void startTest() throws ClassNotFoundException, InterruptedException {
        start=new CountDownLatch(startThead);
        end=new CountDownLatch(threadsNum);
        for (int i = 0; i < threadsNum; i++) {
            Thread thread=new Thread(new Runnable() {

                public void run() {
                    try {
                        ehcacheTest();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        System.out.println(Thread.currentThread().getName()+" exist error ");
                    }               
                }
            },"thread"+i);

            thread.start();

            start.countDown();

        }

        end.await();

        System.out.println("this is end");

    }



    public void ehcacheTest() throws InterruptedException {
        System.out.println("Deamon thread"+Thread.currentThread().isDaemon());
        System.out.println(Thread.currentThread().getName()+" is already");
        start.await();
        String key="a";


        Element element=EhcacheUtil.get(key);
        if (element == null) {
            System.out.println(Thread.currentThread().getName()+" get element is null");
            String result=serviceTest(key);
            EhcacheUtil.put(key, result, 5);
        }else{
            System.out.println(Thread.currentThread().getName()+" get element has something");
            String aString=(String) EhcacheUtil.get(key).getObjectValue();
            System.out.println("aString is:"+aString);
        }

        end.countDown();


    }


    public String serviceTest(String key) {
        int count=1;
        count++;
        System.out.println(Thread.currentThread().getName()+"get into serviceTest "+count+" times");
        return ""+count;
    }
}

不会呀,你确定自己创建的那些线程是没有执行的吗,你在ehcacheTest()方法中加一个休眠看看Thread.currentThread().sleep(10000l);,如果线程没有执行结束,虚拟机肯定是还在运行的

图片说明