首页 > 解决方案 > Is Java thread a daemon 'if and only if' the creating thread is a daemon?

问题描述

According to 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.

Is it correct to use the expression 'if and only if' here?

I thought we can make a daemon thread by using setDaemon(true), even if the main thread is a non-daemon thread.

I want to know if I misunderstood the concept.


here is the code I tried:

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);
    }
}

标签: javaandroidmultithreadingconcurrencydaemon

解决方案


Your understanding is correct but the docs are correct as well.

When you create a new Thread inherits its daemon state from its creating Thread, at this point the new thread is daemon if and only if the creating Thread is daemon as well.

Afterwards you can call setDaemon(...) and change the daemon state but that does not invalidate the original claim. The original claim is basically only talking about the Thread creation, not about its future lifecycle / configuration.

The code in the question just moves the changing of the daemon flag to somewhere else. When you call setDaemon(tf); the thread is already configured to be non-daemon and you simply change that config. Note that the android specification only talks about the Thread, technically the documentation is completely irrelevant in your case since you deal with a WorkerThread. Practically of course most of the documentation still holds true, but precisely the statement about the thread inheriting the daemon state is no longer true since you explicitly changed that behaviour.


推荐阅读