守护线程

2020-05-11  本文已影响0人  秋秋_6403
守护线程

线程分为用户线程和守护线程。
主线程是由虚拟机启动时创建的。
虚拟机必须在用户线程执行完毕才会停止。但是不必等守护线程执行完再停止。只要所有用户线程执行完,只剩下守护线程时,虚拟机就停止了,此时守护线程也就停止了。例如gc线程。
创建的线程默认都是非守护线程。
设置守护线程方法是thread.setDaemon(true)

public class TestThreadDaemon implements Runnable {

    @Override
    public void run() {
        while(true){

            try {
                System.out.println("守护线程运行");
                Thread.sleep(2000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        TestThreadDaemon threadDaemon = new TestThreadDaemon();
        Thread thread = new Thread(threadDaemon);
        thread.setDaemon(true);
        thread.start();

    }
}


程序运行结果·:


运行结果

没有一直打印守护线程运行。

public class TestThreadDaemon implements Runnable {

    @Override
    public void run() {
        while (true) {
            System.out.println("守护线程运行");
        }

    }

    public static void main(String[] args) {
        TestThreadDaemon threadDaemon = new TestThreadDaemon();
        Thread thread = new Thread(threadDaemon);
        thread.setDaemon(true);
        thread.start();
        People people = new People();
        Thread thread2 = new Thread(people);
        thread2.start();

    }
}

class People implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("用户线程执行");

        }
    }
}

程序运行结果:


运行结果

用户线程执行完,守护线程又继续执行了一会是因为虚拟机停止需要一定时间。

上一篇 下一篇

猜你喜欢

热点阅读