Java 中的守护线程是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2213340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:48:19  来源:igfitidea点击:

What is a daemon thread in Java?

javamultithreading

提问by rocker

Can anybody tell me what daemon threads are in Java?

谁能告诉我Java 中的守护进程线程是什么?

回答by b_erb

A daemon thread is a thread that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection.

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

You can use the setDaemon(boolean)method to change the Threaddaemon properties before the thread starts.

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

回答by cletus

Traditionally daemon processes in UNIX were those that were constantly running in background, much like services in Windows.

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

A daemon thread in Java is one that doesn't prevent the JVM from exiting. Specifically the JVM will exit when only daemon threads remain. You create one by calling the setDaemon()method on Thread.

Java 中的守护线程不会阻止 JVM 退出。具体来说,当只剩下守护线程时,JVM 将退出。您可以通过调用setDaemon()on的方法来创建一个Thread

Have a read of Daemon threads.

阅读守护进程线程

回答by Hyman

A daemon threadis a thread that is considered doing some tasks in the background like handling requests or various chronjobs that can exist in an application.

一个守护线程是被认为做了一些任务,这样可以在应用程序中存在处理请求或各种chronjobs后台线程。

When your program only have daemon threadsremaining it will exit. That's because usually these threads work together with normal threads and provide background handling of events.

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

You can specify that a Threadis a daemonone by using setDaemonmethod, they usually don't exit, neither they are interrupted.. they just stop when application stops.

您可以使用方法指定 aThread守护进程setDaemon,它们通常不会退出,也不会被中断..它们只是在应用程序停止时停止。

回答by sateesh

A few more points (Reference: Java Concurrency in Practice)

还有几点(参考:Java Concurrency in Practice

  • When a new thread is created it inherits the daemon status of its parent.
  • When all non-daemon threads finish, the JVM halts, and any remaining daemon threads are abandoned:

    • finally blocks are not executed,
    • stacks are not unwound - the JVM just exits.

    Due to this reason daemon threads should be used sparingly, and it is dangerous to use them for tasks that might perform any sort of I/O.

  • 创建新线程时,它会继承其父线程的守护进程状态。
  • 当所有非守护线程完成时,JVM 停止,并放弃所有剩余的守护线程

    • finally 块没有被执行
    • 堆栈没有展开 - JVM 只是退出。

    由于这个原因,应该谨慎使用守护线程,将它们用于可能执行任何类型 I/O 的任务是危险的。

回答by soubhagini

Daemon Thread and User Threads. Generally all threads created by programmer are user thread (unless you specify it to be daemon or your parent thread is a daemon thread). User thread are generally meant to run our programm code. JVM doesn't terminates unless all the user thread terminate.

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

回答by russ

All the above answers are good. Here's a simple little code snippet, to illustrate the difference. Try it with each of the values of true and false in setDaemon.

以上所有答案都很好。这是一个简单的小代码片段,以说明差异。尝试使用 中的每个 true 和 false 值setDaemon

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 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.
        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
            }
        }
    }
}

回答by Okky

Daemon threads are like a service providers for other threads or objects running in the same process as the daemon thread. Daemon threads are used for background supporting tasks and are only needed while normal threads are executing. If normal threads are not running and remaining threads are daemon threads then the interpreter exits.

守护线程就像是其他线程或对象的服务提供者,这些线程或对象与守护线程运行在同一进程中。守护线程用于后台支持任务,仅在正常线程执行时需要。如果正常线程没有运行并且剩余线程是守护线程,则解释器退出。

For example, the HotJava browser uses up to four daemon threads named "Image Fetcher" to fetch images from the file system or network for any thread that needs one.

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

Daemon threads are typically used to perform services for your application/applet (such as loading the "fiddley bits"). The core difference between user threads and daemon threads is that the JVM will only shut down a program when all user threads have terminated. Daemon threads are terminated by the JVM when there are no longer any user threads running, including the main thread of execution.

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

setDaemon(true/false) ?This method is used to specify that a thread is daemon thread.

设置守护进程(真/假)?该方法用于指定一个线程是守护线程。

public boolean isDaemon() ?This method is used to determine the thread is daemon thread or not.

公共布尔 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");
    }

}

OutPut:

输出:

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>

回答by Chanikag

Daemon thread is just like a normal thread except that the JVM will only shut down when the other non daemon threads are not existing. Daemon threads are typically used to perform services for your application.

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

回答by Manish Malhotra

Daemon threads are as everybody explained, will not constrain JVM to exit, so basically its a happy thread for Application from exit point of view.

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

Want to add that daemon threads can be used when say I'm providing an API like pushing data to a 3rd party server / or JMS, I might need to aggregate data at the client JVM level and then send to JMS in a separate thread. I can make this thread as daemon thread, if this is not a mandatory data to be pushed to server. This kind of data is like log push / aggregation.

想要添加守护线程可以在说我提供 API 时使用,例如将数据推送到 3rd 方服务器/或 JMS,我可能需要在客户端 JVM 级别聚合数据,然后在单独的线程中发送到 JMS。如果这不是要推送到服务器的强制性数据,我可以将此线程设为守护线程。这种数据就像日志推送/聚合。

Regards, Manish

问候, 曼尼什

回答by hans wurst

Daemon threads die when the creator thread exits.

当创建者线程退出时,守护线程就会死亡。

Non-daemon threads (default) can even live longer than the main thread.

非守护线程(默认)甚至可以比主线程活得更长。

if ( threadShouldDieOnApplicationEnd ) {
    thread.setDaemon ( true );
}
thread.start();