Daemon thread in java can be useful to run some tasks in background. When we create a thread in java, by default it’s a user thread and if it’s running JVM will not terminate the program.

Java中的守护程序线程对于在后台运行某些任务很有用。 当我们在java中创建线程时 ,默认情况下它是用户线程,并且如果它正在运行,JVM不会终止程序。

Java中的守护程序线程 (Daemon thread in java)

When a thread is marked as daemon thread, JVM doesn’t wait it to finish to terminate the program. As soon as all the user threads are finished, JVM terminates the program as well as all the associated daemon threads.

当一个线程被标记为守护程序线程时,JVM不会等待它完成以终止程序。 一旦所有用户线程完成,JVM就会终止程序以及所有关联的守护程序线程。

Thread.setDaemon(true) is used to create a daemon thread in java. This method should be invoked before the thread is started otherwise it will throw IllegalThreadStateException.

Thread.setDaemon(true)用于在Java中创建守护程序线程。 应该在启动线程之前调用此方法,否则它将抛出IllegalThreadStateException

We can check if a thread is daemon thread or not by calling isDaemon() method on it.

我们可以通过在线程上调用isDaemon()方法来检查线程是否为守护线程。

Another point is that when a thread is started, it inherits the daemon status of it’s parent thread.

另一点是,当线程启动时,它将继承其父线程的守护程序状态。

Java示例中的守护程序线程 (Daemon Thread in Java Example)

Let’s see a small example of daemon thread in java.

让我们看一下Java中守护线程的一个小例子。

package com.journaldev.threads;public class JavaDaemonThread {public static void main(String[] args) throws InterruptedException {Thread dt = new Thread(new DaemonThread(), "dt");dt.setDaemon(true);dt.start();//continue programThread.sleep(30000);System.out.println("Finishing program");}}class DaemonThread implements Runnable{@Overridepublic void run() {while(true){processSomething();}}private void processSomething() {try {System.out.println("Processing daemon thread");Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}}}

When we execute above daemon thread program, JVM creates first user thread with main() method and then a daemon thread.

当我们执行上述守护程序线程程序时,JVM首先使用main()方法创建用户线程,然后再创建守护程序线程。

When main method is finished, the program terminates and daemon thread is also shut down by JVM.

当main方法完成时,程序终止,并且JVM也关闭了守护程序线程。

Below image shows the output of the above program.

下图显示了以上程序的输出。

If we don’t set the “dt” thread to be run as daemon thread, the program will never terminate even after main thread is finished it’s execution. Notice that DaemonThread is having a while true loop with thread sleep, so it will never terminate on it’s own.

如果我们不将“ dt”线程设置为守护程序线程运行,则即使主线程完成执行,程序也永远不会终止。 请注意, DaemonThread 线程睡眠有一个true循环,因此它永远不会自行终止。

Try to comment the statement to set thread as daemon thread and run the program. You will notice that program runs indefinitely and you will have to manually quit it.

尝试注释该语句以将线程设置为守护程序线程并运行程序。 您会注意到该程序会无限期运行,并且您必须手动退出它。

守护程序线程用法 (Daemon Thread Usage)

Usually we create a daemon thread for functionalities that are not critical to system. For example logging thread or monitoring thread to capture the system resource details and their state. If you are not okay will a thread being terminated, don’t create it as a daemon thread.

通常,我们为对系统不重要的功能创建一个守护线程。 例如,日志记录线程或监视线程可捕获系统资源详细信息及其状态。 如果您不满意,线程将被终止,请不要将其创建为守护线程。

Also it’s better to avoid daemon threads for IO operations because it can cause resource leak when program just terminates and resources are not closed properly.

另外,最好避免使用守护程序线程进行IO操作,因为当程序刚刚终止且资源未正确关闭时,它可能导致资源泄漏。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/1072/daemon-thread-in-java

Java中的守护程序线程相关推荐

  1. 什么是Java中的守护程序线程?

    谁能告诉我Java中有哪些守护程序线程? #1楼 守护程序线程就像其他与守护程序线程在同一进程中运行的线程或对象的服务提供者一样. 守护程序线程用于后台支持任务,仅在执行正常线程时才需要. 如果正常线 ...

  2. java中的后台线程、前台线程、守护线程区别

    java中的后台线程.前台线程.守护线程区别 区别和联系 区别 联系 区别和联系 区别 后台线程和守护线程是一样的. 后台线程不会阻止进程的终止,而前台线程会, 可以在任何时候将前台线程修改为后台线程 ...

  3. Java中如何实现线程的超时中断

    转载自  Java中如何实现线程的超时中断 背景 之前在实现熔断降级组件的时候,需要实现接口请求的超时中断.意思是,业务在使用熔断降级功能时,在平台上设置了一个超时时间,如果请求进入熔断器开始计时,接 ...

  4. Java中枚举的线程安全性及序列化问题

    转载自  Java中枚举的线程安全性及序列化问题 Java SE5提供了一种新的类型-Java的枚举类型,关键字enum可以将一组具名的值的有限集合创建为一种新的类型,而这些具名的值可以作为常规的程序 ...

  5. java创建单线程计时器_我们如何在Java中实现计时器线程?

    该定时器类计划任务一次或多次给定的时间运行.它也可以作为后台程序线程在后台运行.要将Timer与守护程序线程相关联,有一个带有布尔值的构造函数.计时器以固定的延迟和固定的速率安排任务.在固定的延迟中, ...

  6. java中我爱你_Java线程学习(转)

    编写具有多线程能力的程序经常会用到的方法有: run(),start(),wait(),notify(),notifyAll(),sleep(),yield(),join() 还有一个重要的关键字:s ...

  7. java中等待所有线程都执行结束

    使用CountDownLatch,这其实是最优雅的写法了,每个线程完成后都去将计数器减一,最后完成时再来唤醒 @Test public void testThreadSync3() { final V ...

  8. Java中怎样创建线程安全的方法

    面试问题: 下面的方法是否线程安全?怎样让它成为线程安全的方法? class MyCounter {private static int counter = 0;public static int g ...

  9. java中四种线程池的区别

    本文按: 一. 线程池的使用 二. 几种线程池的区别 三. 如何合理配置线程池 一.线程池的使用 在Java中,通常使用Executors 获取线程池.常用的线程池有以下几种: (1)CachedTh ...

最新文章

  1. iphone7像素_iPhone 7能否再战三年?这几点因素你得考虑到!
  2. 这个程序,有点意思!
  3. golang类型断言及检测其是否断言成功
  4. audio标签不展示_设计标签式PPT:排版简洁明了,强烈信息秩序感,你想试试吗?...
  5. ConEmu状态栏的设置介绍
  6. LeetCode 第 22 场双周赛(220/2041,前10.8%)
  7. .netframework游戏编程入门——模拟魔兽学院永远的羁绊
  8. 《2020饿了么蓝骑士报告》:贫困县骑手月入5800元 成脱贫新兴力量
  9. ps4pro服务器维护,PS4 | PS4 Pro 常见问题 | PlayStation
  10. 我有机器人合体成一个大力神_变形金刚动漫人物:狂派霸天虎挖地虎合体金刚-大力神...
  11. 清明节,如何用代码让网页变灰
  12. select学习小demo--实现网页换肤
  13. mysql 安装部署
  14. Go基础:切片的地址和扩容
  15. redis配置文件下载
  16. 浅谈CURD系统和CRQS系统
  17. 1072 开学寄语 (20分)
  18. 如何打包c#编写的程序
  19. html文件只能打印一页,javascript – 使用window.print()打印巨大的表只打印一页
  20. 查询7日内的展示数据

热门文章

  1. [NOIP2011]聪明的质检员
  2. 一步步学习微软InfoPath2010和SP2010--第十二章节--管理和监控InfoPath Form Services(IPFS)(4)--监控含图片控件的Products表单...
  3. mysql 查询表注释
  4. Cut Curve randomly
  5. [转载] python基础知识三——try与except处理异常语句
  6. [转载] Python字符串isdecimal() isdigit()isnumeric()等判断方法的区分。
  7. [转载] 使用Python在Pandas Dataframe中建立索引
  8. [转载] numpy数组遍历找到个数最多的元素
  9. bzoj 2553 [BeiJing2011]禁忌——AC自动机+概率DP+矩阵
  10. jQuery 异步和同步请求