java守护程序线程 [英] java daemon threads

查看:156
本文介绍了java守护程序线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,当封闭线程完成后,守护程序线程是否会停止工作?或者守护程序线程将在主线程完成后停止?

Hi all, will daemon thread stop working when the enclosing it thread will finish? Or daemon thread will stop when the "main" thread will finish?

我在jre6上测试了这个例子,结果是守护程序线程停止工作时将它封闭完成。请注意,java docs表示当没有其他应用程序线程时,守护程序线程将被终止。当父母非守护程序线程仍然存在时,并不是说守护程序线程被杀死。

I tested this example on jre6 and result was daemon thread stopped working when the enclosing it thread finished. Notice that java docs said that daemon threads are killed when no other application threads remain. And it's not said that daemon threads are killed when parent non-daemon thread remains.

请给我答案。请寄给我关于这个问题的任何材料。
对不起我的英文。

Please give me answers. Please send me any material about this question. Sorry for my English.

public class Main {
    public static void main(String[] args) {
        Thread simple = new Thread(new SimpleTask());
        simple.start();
    }
}

class SimpleTask implements Runnable {
    public void run() {
        try {
            Thread daemon = new Thread(new DaemonTask());
            daemon.setDaemon(true);
            daemon.start();
            Thread.sleep(5000);
        } catch (InterruptedException e) {}
    };
}

class DaemonTask implements Runnable {
    public void run() {
        int i = 0;
        while (true) {
            try {
                System.out.println("a" + (i++));
                Thread.sleep(500);
            } catch (InterruptedException e) {}
        }
    }
}


推荐答案


当封闭它的线程完成后,守护程序线程会停止工作吗?

will daemon thread stop working when the enclosing it thread will finish?

Java中没有封闭线程这样的概念。有线程,但它们很少使用。

There's no such concept as an "enclosing thread" in Java. There are thread groups but they're rarely used.

守护程序线程只是线程,不会阻止JVM终止。如果没有任何非守护程序线程,JVM将终止。如果仍有一些非守护程序线程正在执行,JVM将继续运行,包括任何守护程序线程 - 无论启动那些守护程序线程的线程是否已完成。

Daemon threads are simply threads which don't stop the JVM from terminating. When there aren't any non-daemon threads left, the JVM will terminate. If there are still some non-daemon threads executing, the JVM will keep going, including any daemon threads - whether or not the threads that started those daemon threads have finished.

这篇关于java守护程序线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆