Java守护线程

java中的后台线程,是Thread实例设置了setDaemon(true),即将daemon属性设置为了true。 主线程运行结束,后台线程会被jvm中断,退出程序。

public static void main(String[] args) {
    Thread thread = new Thread() {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("thread run");
            }
        }
    };
    //设置线程为守护线程
    thread.setDaemon(true);
    thread.start();


    try {
        Thread.sleep(3 * 1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("main end");
}

运行结果:

thread run
thread run
main end
thread run

Process finished with exit code 0

可以看到在主线程退出之后,deamon线程也就被终止了,同时程序也就退出了。


我们对上面程序稍作改动,将t.setDaemon(true)注释掉,再看下运行结果。

    public static void main(String[] args) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1 * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println("thread run");
                }
            }
        };
        //设置线程为守护线程
//        thread.setDaemon(true);
        thread.start();


        try {
            Thread.sleep(3 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("main end");
    }

运行结果:

thread run
thread run
thread run
main end
thread run
thread run
thread run
thread run
thread run
thread run
thread run
thread run
thread run
thread run

可以看到在主线程退出之后,子线程还在继续执行,这是因为线程t默认情况下是非守护线程,尽管主线程退出了,他还是在继续执行着。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值