Java 线程是守护进程吗 'if and only if' 创建的线程是守护进程?

Is Java thread a daemon 'if and only if' the creating thread is a daemon?

根据Android documentation

When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.

这里使用表达式'if and only if'是否正确?

我想我们可以使用 setDaemon(true) 创建一个守护线程,即使主线程是一个非守护线程。

我想知道我是否误解了这个概念。


这是我试过的代码:

public class MyClass {
    public static void main(String[] args) {
        boolean isDaemon;
        isDaemon = Thread.currentThread().isDaemon();
        System.out.println("Is main thread daemon?:" + isDaemon);
        new WorkerThread(true).start();
    }
}

class WorkerThread extends Thread {
    public WorkerThread(boolean tf) {
        setDaemon(tf);
    }

    public void run() {
        boolean isDaemon;
        isDaemon = Thread.currentThread().isDaemon();
        System.out.println("Is worker thread daemon?:" + isDaemon);
    }
}

你的理解是正确的,文档也是正确的。

当您创建一个新线程时,它会从其创建线程继承其守护进程状态,此时新线程是守护进程当且仅当创建线程也是守护进程时。

之后您可以调用 setDaemon(...) 并更改守护程序状态,但这不会使原始声明无效。原来的说法基本上只是在谈论Thread的创建,而不是它未来的生命周期/配置。

问题中的代码只是将守护程序标志的更改移动到其他地方。当您调用 setDaemon(tf); 时,线程已配置为非守护进程,您只需更改该配置即可。请注意,android 规范仅讨论 Thread,从技术上讲,文档与您的情况完全无关,因为您处理的是 WorkerThread。实际上,当然大部分文档仍然适用,但恰恰是关于线程继承守护进程状态的声明不再正确,因为您显式更改了该行为。