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


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

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


传统上,UNIX中的守护进程是那些不断在后台运行的进程,就像Windows中的服务一样。

Java中的守护线程是不阻止JVM退出的线程。特别是当只剩下守护线程时,JVM将退出。您可以通过调用线程上的setDaemon()方法来创建一个。

读取Daemon线程。


守护线程是在后台执行一些任务的线程,比如处理请求或应用程序中可能存在的各种chronjob。

当你的程序只剩下守护线程时,它将退出。这是因为这些线程通常与普通线程一起工作,并提供事件的后台处理。

你可以使用setDaemon方法指定一个线程是守护线程,它们通常不会退出,也不会被中断。当应用程序停止时,它们就会停止。


再讲一点(参考:Java并发实践)

当创建一个新线程时,它将继承其守护进程状态 的父母。 当所有非守护进程线程完成时,JVM停止,并放弃所有剩余的守护进程线程: 最后,块不执行, 栈不会被解开——JVM只是退出。 由于这个原因,应该谨慎使用守护线程,将它们用于可能执行任何类型的I/O的任务是危险的。


守护线程和用户线程。通常程序员创建的所有线程都是用户线程(除非你指定它为守护线程或者你的父线程是守护线程)。用户线程通常用于运行我们的程序代码。除非所有用户线程都终止,否则JVM不会终止。


以上答案都是好的。下面是一个简单的小代码片段,以说明两者的区别。在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
            }
        }
    }
}

守护线程就像一个服务提供者,为运行在与守护线程相同进程中的其他线程或对象提供服务。守护线程用于后台支持任务,只有在正常线程执行时才需要守护线程。如果正常线程不运行,其余线程是守护线程,则解释器退出。

例如,HotJava浏览器使用最多4个名为“Image Fetcher”的守护线程从文件系统或网络中为任何需要的线程获取图像。

守护线程通常用于为应用程序/applet执行服务(例如加载“fiddley bits”)。用户线程和守护线程之间的核心区别在于,JVM只会在所有用户线程都终止时关闭程序。当不再有任何用户线程在运行(包括执行主线程)时,守护线程将由JVM终止。

setDaemon(真/假)?此方法用于指定一个线程是守护线程。

公共boolean isDaemon() ?此方法用于确定线程是否是守护线程。

Eg:

public class DaemonThread extends Thread {
    public void run() {
        System.out.println("Entering run method");

        try {
            System.out.println("In run Method: currentThread() is" + Thread.currentThread());

            while (true) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException x) {}

                System.out.println("In run method: woke up again");
            }
        } finally {
            System.out.println("Leaving run Method");
        }
    }
    public static void main(String[] args) {
        System.out.println("Entering main Method");

        DaemonThread t = new DaemonThread();
        t.setDaemon(true);
        t.start();

        try {
            Thread.sleep(3000);
        } catch (InterruptedException x) {}

        System.out.println("Leaving main method");
    }

}

输出:

C:\java\thread>javac DaemonThread.java

C:\java\thread>java DaemonThread
Entering main Method
Entering run method
In run Method: currentThread() isThread[Thread-0,5,main]
In run method: woke up again
In run method: woke up again
In run method: woke up again
In run method: woke up again
In run method: woke up again
In run method: woke up again
Leaving main method

C:\j2se6\thread>

守护线程就像一个普通的线程,除了JVM只会在其他非守护线程不存在时关闭。守护进程线程通常用于为应用程序执行服务。


正如大家所解释的,守护线程不会限制JVM退出,所以基本上从退出的角度来看,它对应用程序来说是一个快乐的线程。

想要添加守护线程,当我提供一个API,比如将数据推送到第三方服务器/或JMS时,我可能需要在客户端JVM级别聚合数据,然后在一个单独的线程中发送到JMS。我可以使这个线程作为守护线程,如果这不是一个强制数据被推送到服务器。 这类数据类似于日志推送/聚合。

问候, Manish


Java中的守护线程是指运行在后台的线程,主要由JVM创建,用于执行后台任务,如垃圾收集和其他家政任务。

注意事项:

Any thread created by main thread, which runs main method in Java is by default non daemon because Thread inherits its daemon nature from the Thread which creates it i.e. parent Thread and since main thread is a non daemon thread, any other thread created from it will remain non-daemon until explicitly made daemon by calling setDaemon(true). Thread.setDaemon(true) makes a Thread daemon but it can only be called before starting Thread in Java. It will throw IllegalThreadStateException if corresponding Thread is already started and running.

Java中守护线程与非守护线程的区别:

1) JVM在存在之前不会等待任何守护线程完成。

2)当JVM终止时,守护线程与用户线程被区别对待,最终块不被调用,堆栈不受伤,JVM只是退出。


Java有一种特殊的线程,称为守护线程。

非常低的优先级。 仅在同一程序没有其他线程正在运行时执行。 当守护线程结束时,JVM结束程序,完成这些线程 程序中运行的唯一线程。

守护线程用于什么?

通常用作普通线程的服务提供者。 通常有一个等待服务请求或执行线程任务的无限循环。 他们不能做重要的工作。(因为我们不知道它们什么时候会有CPU时间,如果没有任何其他线程在运行,它们可以在任何时间完成。)

这类线程的一个典型示例是Java垃圾收集器。

有更多的…

在调用start()方法之前,只能调用setDaemon()方法。线程运行后,就不能修改它的守护进程状态。 使用isDaemon()方法检查线程是守护线程还是用户线程。


守护线程是在进程的其他非守护线程仍在运行时在后台运行的线程。因此,当所有非守护进程线程完成时,守护进程线程将终止。非守护进程线程的一个例子是运行Main的线程。 通过在线程启动之前调用setDaemon()方法,将线程设置为守护进程

更多参考:Java中的守护进程线程


Daemon thread is like daemon process which is responsible for managing resources,a daemon thread is created by the Java VM to serve the user threads. example updating system for unix,unix is daemon process. child of daemon thread is always daemon thread,so by default daemon is false.you can check thread as daemon or user by using "isDaemon()" method. so daemon thread or daemon process are basically responsible for managing resources. for example when you starting jvm there is garbage collector running that is daemon thread whose priority is 1 that is lowest,which is managing memory. jvm is alive as long as user thread is alive,u can not kill daemon thread.jvm is responsible to kill daemon threads.


守护进程: d(isk) a(nd) e(xecution) mon(itor) or or from de(vice) mon(itor)

Daemon(计算)的定义:

处理打印假脱机和文件传输等服务请求的后台进程,在不需要时处于休眠状态。

——来源:牛津词典英文版

Java中的守护线程是什么?

Daemon threads can shut down any time in between their flow, Non-Daemon i.e. user thread executes completely. Daemon threads are threads that run intermittently in the background as long as other non-daemon threads are running. When all of the non-daemon threads complete, daemon threads terminates automatically. Daemon threads are service providers for user threads running in the same process. The JVM does not care about daemon threads to complete when in Running state, not even finally block also let execute. JVM do give preference to non-daemon threads that is created by us. Daemon threads acts as services in Windows. The JVM stops the daemon threads when all user threads (in contrast to the daemon threads) are terminated. Hence daemon threads can be used to implement, for example, a monitoring functionality as the thread is stopped by the JVM as soon as all user threads have stopped.


我想澄清一个误解:

Assume that if daemon thread (say B) is created within user thread (say A); then ending of this user thread/parent thread (A) will not end the daemon thread/child thread (B) it has created; provided user thread is the only one currently running. So there is no parent-child relationship on thread ending. All daemon threads (irrespective of where it is created) will end once there is no single live user thread and that causes JVM to terminate. Even this is true for both (parent/child) are daemon threads. If a child thread created from a daemon thread then that is also a daemon thread. This won't need any explicit daemon thread flag setting. Similarly if a child thread created from a user thread then that is also a user thread, if you want to change it, then explicit daemon flag setting is needed before start of that child thread.


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

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


对我来说,守护线程就像用户线程的管家。 如果所有用户线程都已完成,守护进程线程就没有任务 JVM杀死。 我在YouTube视频里解释过了。


让我们只讨论工作示例中的代码。我喜欢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

守护进程线程通常被称为“服务提供者”线程。这些线程不应该用来执行程序代码,而应该用来执行系统代码。这些线程与您的代码并行运行,但JVM可以随时终止它们。当JVM没有发现用户线程时,它将停止用户线程,所有守护进程线程立即终止。我们可以使用以下方法将非守护线程设置为守护线程:

setDaemon(true)

守护线程类似于助手线程。非daemon线程就像前面的表演者。助手帮助表演者完成一项工作。工作完成后,执行者不再需要帮助来执行。由于不需要帮助,助手们离开了这个地方。因此,当非守护线程的任务结束时,守护线程就会离开。


当最后一个非守护进程线程执行完成时,JVM将完成这项工作。默认情况下,JVM将创建一个线程作为非守护进程,但我们可以通过setDaemon(true)方法将线程创建为守护进程。Daemon线程的一个很好的例子是GC线程,它将在所有非Daemon线程完成后立即完成它的工作。


下面是一个示例,用于测试在jvm由于不存在用户线程而退出时守护线程的行为。

请注意下面输出的倒数第二行,当主线程退出时,守护线程也死了,并且没有在finally块中打印finally executed9语句。这意味着如果由于不存在用户线程而导致JVM退出,守护线程finally块内关闭的任何i/o资源都不会被关闭。

public class DeamonTreadExample {

public static void main(String[] args) throws InterruptedException {

    Thread t = new Thread(() -> {
        int count = 0;
        while (true) {
            count++;
            try {
                System.out.println("inside try"+ count);
                Thread.currentThread().sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                System.out.println("finally executed"+ count);
            }
        }
    });
    t.setDaemon(true);
    t.start();

    Thread.currentThread().sleep(10000);
    System.out.println("main thread exited");
  }
}

输出

inside try1
finally executed1
inside try2
finally executed2
inside try3
finally executed3
inside try4
finally executed4
inside try5
finally executed5
inside try6
finally executed6
inside try7
finally executed7
inside try8
finally executed8
inside try9
finally executed9
inside try10
main thread exited

答案已经有很多了;然而,也许我可以更清楚地解释这一点,因为当我阅读Daemon Threads时,最初,我有一种感觉,我很好地理解了它;然而,在玩了它并调试了一下之后,我发现了一个奇怪的行为。

我被教导:

如果我想让线程在主线程有序完成执行后立即死亡,我应该将其设置为Diamond。

我尝试了什么:

我从主线程中创建了两个线程,我只将其中一个设置为菱形; 在主线程有序完成执行后,那些新创建的线程都没有退出,但我预计,守护线程应该已经退出; 我浏览了许多博客和文章,到目前为止,我找到的最好、最清晰的定义来自《Java并发实践》一书,它非常清楚地指出:

7.4.2守护线程

Sometimes you want to create a thread that performs some helper function but you don’t want the existence of this thread to prevent the JVM from shutting down. This is what daemon threads are for. Threads are divided into two types: normal threads and daemon threads. When the JVM starts up, all the threads it creates (such as garbage collector and other housekeeping threads) are daemon threads, except the main thread. When a new thread is created, it inherits the daemon status of the thread that created it, so by default any threads created by the main thread are also normal threads. Normal threads and daemon threads differ only in what happens when they exit. When a thread exits, the JVM performs an inventory of running threads, and if the only threads that are left are daemon threads, it initiates an orderly shutdown. When the JVM halts, any remaining daemon threads are abandoned— finally blocks are not executed, stacks are not unwound—the JVM just exits. Daemon threads should be used sparingly—few processing activities can be safely abandoned at any time with no cleanup. In particular, it is dangerous to use daemon threads for tasks that might perform any sort of I/O. Daemon threads are best saved for “housekeeping” tasks, such as a background thread that periodically removes expired entries from an in-memory cache.


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()


Java守护线程

(守护进程)

Java使用用户线程和守护进程线程概念。

JVM流

1. If there are no `user treads` JVM starts terminating the program
2. JVM terminates all `daemon threads` automatically without waiting when they are done
3. JVM is shutdown

正如你所看到的,守护线程是用户线程的服务线程。

守护线程是低优先级线程。 线程从父线程继承它的属性。要从外部设置它,你可以在启动它之前使用setDaemon()方法或通过isDaemon()检查它


守护线程

在后台运行的线程称为守护线程。

Daemon线程示例:

垃圾收集器。 信号分配器。

守护线程的目标:

守护进程线程的主要目标是为非守护进程线程提供支持。

有关守护线程的其他信息:

通常,守护线程在MIN_PRIORITY中运行,但是,也可以使用MAX_PRIORITY运行守护线程。 示例:当需要额外的内存时,GC通常以MIN_PRIORITY优先级运行。JVM将GC的优先级从MIN_PRIORITY增加到MAX_PRIORITY。


一旦线程已经启动,就不能将其从守护线程更改为非守护线程,这会导致IllegalThreadStateException异常。 例子: public static void main(String[] args) { Thread.currentThread () .setDaemon(真正的); } 输出: java.lang.IllegalThreadStateException线程异常 在java.base / java.lang.Thread.setDaemon (Thread.java: 1403)


If we are branching off a thread, the child thread inherits the nature of the parent thread. If the parent thread is a non-daemon thread automatically the child thread will be non-daemon as well and if the parent thread is a daemon, the child thread will be a daemon as well. class Scratch { public static void main(String[] args) { CustomThread customThread = new CustomThread(); customThread.start(); } } class CustomThread extends Thread{ @Override public void run() { System.out.println(currentThread().isDaemon()); } } Output: false


When the last non-daemon thread terminates, all the daemon threads get terminated automatically. class Scratch { public static void main(String[] args) { System.out.println("Main Thread Started."); CustomThread customThread = new CustomThread(); customThread.setDaemon(true); customThread.start(); System.out.println("Main Thread Finished."); } } class CustomThread extends Thread{ @Override public void run() { System.out.println("Custom Thread Started."); try { sleep(2000); } catch (InterruptedException ignore) {} System.out.println("Custom Thread Finished."); //Won't get executed. } } Output: Main Thread Started. Main Thread Finished. Custom Thread Started.


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

守护进程的线程

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

用户线程

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

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

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