Java并发编程

Java并发编程 - 用户线程和守护线程

2018-09-09  本文已影响9人  HRocky

用户线程和守护线程

Stackoverflow中关于守护线程有如下比较好的解释:

Daemon threads are like assistants. Non-Daemon i.e. user threads are like front performers. Assistants help performers to complete a job. When the job is completed, no help is needed by performers to perform anymore. As no help is needed the assistants leave the place. So when the jobs of Non-Daemon threads is over, Daemon threads march away.

使用守护线程的目的

关于守护线程的一些重要点

使用守护线程

案例一

public class DaemonThread {

    public static void main(String[] args) throws InterruptedException {
        
        Thread t = new Thread() {

            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getName() + " running");
                    Thread.sleep(10000);
                    System.out.println(Thread.currentThread().getName() + " done");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        };

        t.setDaemon(true);
        // runnable -> running|dead|blocked
        t.start();

        Thread.sleep(5000);
        System.out.println(Thread.currentThread().getName());

    }
    
}

执行结果:main线程执行结束后,t线程就会停止。

案例二

public class DaemonThread1 {

    public static void main(String[] args)  {
        
        Thread t = new Thread() {

            @Override
            public void run() {

                Thread innerThread = new Thread() {

                    @Override
                    public void run() {
                        try {
                            while(true) {
                                System.out.println("Do something for health check.");
                                Thread.sleep(10000);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                };

                innerThread.setDaemon(true);
                innerThread.start();

                try {
                    Thread.sleep(1000);
                    System.out.println("T thread finish done.");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        };

        // runnable -> running|dead|blocked
        t.start();
    }
    
}

执行结果:t线程停止后,innerThread就会停止。

上一篇 下一篇

猜你喜欢

热点阅读