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


当前回答

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

其他回答

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

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

读取Daemon线程。

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.

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

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

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

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

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