java里的主线程和子线程以及finally不会执行的特殊情况

46 阅读1分钟

如下代码:

public class ThreadTest {
    public static class UserThread extends Thread{
        @Override
        public void run() {
            while (!isInterrupted()){
                System.out.println(1);
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        UserThread userThread = new UserThread();
//        userThread.setDaemon(true);
        userThread.start();

    }
}

开启main方法后会一直打印1,1…,但是当开启了注释为守护线程,那么直接终止main方法,并且守护线程直接死亡,并且设置为守护线程后,如果在run方法里有finally,也不会执行。