Java 虚拟线程是否为守护线程

Java About 1,837 words

结论

Java中的虚拟线程默认是守护线程,且不能被修改为非守护线程

守护线程:当JVM退出时,JVM不会等守护线程执行完毕才退出,等所有非守护线程执行完毕后JVM就会退出。

源码

ThreadisDaemon()方法,当线程是虚拟线程时直接返回true

ThreadsetDaemon()方法,当线程是虚拟线程时想要将虚拟线程改为非守护线程会抛出异常。

package java.lang;

public class Thread implements Runnable {

    /**
     * Tests if this thread is a daemon thread.
     * The daemon status of a virtual thread is always {@code true}.
     *
     * @return  {@code true} if this thread is a daemon thread;
     *          {@code false} otherwise.
     * @see     #setDaemon(boolean)
     */
    public final boolean isDaemon() {
        if (isVirtual()) {
            return true;
        } else {
            return holder.daemon;
        }
    }
    
    /**
     * Marks this thread as either a <i>daemon</i> or <i>non-daemon</i> thread.
     * The <a href="Runtime.html#shutdown">shutdown sequence</a> begins when all
     * started non-daemon threads have terminated.
     *
     * <p> The daemon status of a virtual thread is always {@code true} and cannot be
     * changed by this method to {@code false}.
     *
     * <p> This method must be invoked before the thread is started. The behavior
     * of this method when the thread has terminated is not specified.
     *
     * @param  on
     *         if {@code true}, marks this thread as a daemon thread
     *
     * @throws  IllegalArgumentException
     *          if this is a virtual thread and {@code on} is false
     * @throws  IllegalThreadStateException
     *          if this thread is {@linkplain #isAlive alive}
     */
    public final void setDaemon(boolean on) {
        if (isVirtual() && !on)
            throw new IllegalArgumentException("'false' not legal for virtual threads");
        if (isAlive())
            throw new IllegalThreadStateException();
        if (!isVirtual())
            daemon(on);
    }
    
}
Views: 13 · Posted: 2025-12-19

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓
Today In History
Browsing Refresh