有人能告诉我Java中的守护线程是什么吗?


当前回答

让我们只讨论工作示例中的代码。我喜欢russ上面的回答,但为了消除我的疑虑,我稍微加强了一下。我运行了两次,一次工作线程设置为deamon true (deamon线程),另一次设置为false(用户线程)。它确认守护线程在主线程结束时结束。

public class DeamonThreadTest {

public static void main(String[] args) {

    new WorkerThread(false).start();    //set it to true and false and run twice.

    try {
        Thread.sleep(7500);
    } catch (InterruptedException e) {
        // handle here exception
    }

    System.out.println("Main Thread ending");
    }
   }

   class WorkerThread extends Thread {

    boolean isDeamon;

    public WorkerThread(boolean isDeamon) {
        // When false, (i.e. when it's a user thread),
        // the Worker thread continues to run.
        // When true, (i.e. when it's a daemon thread),
        // the Worker thread terminates when the main
        // thread terminates.
        this.isDeamon = isDeamon;
        setDaemon(isDeamon);
    }

    public void run() {
        System.out.println("I am a " + (isDeamon ? "Deamon Thread" : "User Thread (none-deamon)"));

        int counter = 0;

        while (counter < 10) {
            counter++;
            System.out.println("\tworking from Worker thread " + counter++);

            try {
                sleep(5000);
            } catch (InterruptedException e) {
                // handle exception here
            }
        }
        System.out.println("\tWorker thread ends. ");
    }
}



result when setDeamon(true)
=====================================
I am a Deamon Thread
    working from Worker thread 0
    working from Worker thread 1
Main Thread ending

Process finished with exit code 0


result when setDeamon(false)
=====================================
I am a User Thread (none-deamon)
    working from Worker thread 0
    working from Worker thread 1
Main Thread ending
    working from Worker thread 2
    working from Worker thread 3
    working from Worker thread 4
    working from Worker thread 5
    working from Worker thread 6
    working from Worker thread 7
    working from Worker thread 8
    working from Worker thread 9
    Worker thread ends. 

Process finished with exit code 0

其他回答

在Java中,守护线程是一种不阻止Java虚拟机(JVM)退出的线程类型。 守护线程的主要目的是执行后台任务,特别是一些例行的周期性任务或工作。JVM退出时,守护进程线程也会死亡。

通过设置thread. setdaemon (true),线程变成守护线程。但是,您只能在线程启动之前设置这个值。

守护线程是在程序完成但线程仍在运行时不阻止JVM退出的线程。守护进程线程的一个例子是垃圾收集。

您可以使用setDaemon(boolean)方法在线程启动之前更改线程守护进程属性。

Daemon threads are those threads which provide general services for user threads (Example : clean up services - garbage collector) Daemon threads are running all the time until kill by the JVM Daemon Threads are treated differently than User Thread when JVM terminates , finally blocks are not called JVM just exits JVM doesn't terminates unless all the user threads terminate. JVM terminates if all user threads are dies JVM doesn't wait for any daemon thread to finish before existing and finally blocks are not called If all user threads dies JVM kills all the daemon threads before stops When all user threads have terminated, daemon threads can also be terminated and the main program terminates setDaemon() method must be called before the thread's start() method is invoked Once a thread has started executing its daemon status cannot be changed To determine if a thread is a daemon thread, use the accessor method isDaemon()

以上答案都是好的。下面是一个简单的小代码片段,以说明两者的区别。在setDaemon中分别尝试true和false值。

public class DaemonTest {
    
    public static void main(String[] args) {
        new WorkerThread().start();

        try {
            Thread.sleep(7500);
        } catch (InterruptedException e) {
            // handle here exception
        }

        System.out.println("Main Thread ending") ;
    }

}

class WorkerThread extends Thread {
    
    public WorkerThread() {
        // When false, (i.e. when it's a non daemon thread),
        // the WorkerThread continues to run.
        // When true, (i.e. when it's a daemon thread),
        // the WorkerThread terminates when the main 
        // thread or/and user defined thread(non daemon) terminates.
        setDaemon(true); 
    }
    
    public void run() {
        int count = 0;

        while (true) {
            System.out.println("Hello from Worker "+count++);

            try {
                sleep(5000);
            } catch (InterruptedException e) {
                // handle exception here
            }
        }
    }
}

java线程中的用户线程与守护线程

守护进程的线程

这些线程在Java中是低优先级的线程,在后台运行以执行诸如垃圾收集之类的任务。Java中的守护线程也是一个服务提供者线程,它向用户线程提供服务。

用户线程

这些线程是高优先级线程。JVM将等待任何用户线程在终止它之前完成它的任务

“请记住用户和守护线程都包装在操作系统线程上”

最近OpenJdk在Loom项目中提出了虚拟线程(它们也是基于用户的),你可以在这里找到更多关于Java虚拟机线程的纤维和延续。