有人能告诉我Java中的守护线程是什么吗?
当前回答
守护线程和用户线程。通常程序员创建的所有线程都是用户线程(除非你指定它为守护线程或者你的父线程是守护线程)。用户线程通常用于运行我们的程序代码。除非所有用户线程都终止,否则JVM不会终止。
其他回答
守护线程和用户线程。通常程序员创建的所有线程都是用户线程(除非你指定它为守护线程或者你的父线程是守护线程)。用户线程通常用于运行我们的程序代码。除非所有用户线程都终止,否则JVM不会终止。
守护线程是在进程的其他非守护线程仍在运行时在后台运行的线程。因此,当所有非守护进程线程完成时,守护进程线程将终止。非守护进程线程的一个例子是运行Main的线程。 通过在线程启动之前调用setDaemon()方法,将线程设置为守护进程
更多参考:Java中的守护进程线程
守护进程: 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.
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停止,并放弃所有剩余的守护进程线程: 最后,块不执行, 栈不会被解开——JVM只是退出。 由于这个原因,应该谨慎使用守护线程,将它们用于可能执行任何类型的I/O的任务是危险的。
推荐文章
- 指定的子节点已经有一个父节点。你必须先在子对象的父对象上调用removeView() (Android)
- 对于一个布尔字段,它的getter/setter的命名约定是什么?
- 如何获得当前屏幕方向?
- 如何在Android中渲染PDF文件
- 如何计算一个元素在列表中出现的次数
- c++中类似于java的instanceof
- 我如何解决错误“minCompileSdk(31)指定在一个依赖的AAR元数据”在本机Java或Kotlin?
- 如何POST表单数据与Spring RestTemplate?
- Mockito中检测到未完成的存根
- 我应该如何复制字符串在Java?
- “while(true)”循环有那么糟糕吗?
- 这个方法签名中的省略号(…)是干什么用的?
- Java:如何测试调用System.exit()的方法?
- 带有返回类型的Java方法在没有返回语句的情况下编译
- Java“此语言级别不支持lambda表达式”