http://blog.csdn.net/mq612/article/details/1520571

守护线程(Daemon)

Java有两种Thread:“守护线程Daemon”与“用户线程User”。
我们之前看到的例子都是用户,守护线程是一种“在后台提供通用性支持”的线程,它并不属于程序本体。
从字面上我们很容易将守护线程理解成是由虚拟机(virtual machine)在内部创建的,而用户线程则是自己所创建的。事实并不是这样,任何线程都可以是“守护线程Daemon”或“用户线程User”。他们在几乎每个方面都是相同的,唯一的区别是判断虚拟机何时离开:
用户线程:Java虚拟机在它所有非守护线程已经离开后自动离开。
守护线程:守护线程则是用来服务用户线程的,如果没有其他用户线程在运行,那么就没有可服务对象,也就没有理由继续下去。
setDaemon(boolean on)方法可以方便的设置线程的Daemon模式,true为Daemon模式,false为User模式。setDaemon(boolean on)方法必须在线程启动之前调用,当线程正在运行时调用会产生异常。isDaemon方法将测试该线程是否为守护线程。值得一提的是,当你在一个守护线程中产生了其他线程,那么这些新产生的线程不用设置Daemon属性,都将是守护线程,用户线程同样。
import java.io.IOException;
/**
* 守护线程在没有用户线程可服务时自动离开
* @author 五斗米
* @blog http://blog.csdn.net/mq612
*/
public class TestMain4 extends Thread {
public TestMain4() {
}
/**
* 线程的run方法,它将和其他线程同时运行
*/
public void run() {
for(int i = 1; i <= 100; i++){
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.println(i);
}
}
public static void main(String [] args){
TestMain4 test = new TestMain4();
test.setDaemon(true);
test.start();
System.out.println("isDaemon = " + test.isDaemon());
try {
System.in.read(); // 接受输入,使程序在此停顿,一旦接收到用户输入,main线程结束,守护线程自动结束
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

例:我们所熟悉的 Java 垃圾回收线程就是一个典型的守护线程,当我们的程序中不再有任何运行中的 Thread ,程序就不会再产生垃圾,垃圾回收器也就无事可做,所以当垃圾回收线程是 Java 虚拟机上仅剩的线程时, Java 虚拟机会自动离开。

===============

http://liujinpan75.iteye.com/blog/653337

所谓守护线程就是运行在程序后台的线程,程序的主线程Main(比方java程序一开始启动时创建的那个线程)不会是守护线程  
2.Daemon thread在Java里面的定义是,如果虚拟机中只有Daemon thread 在运行,则虚拟机退出。 
  虚拟机中可能会同时有很多个线程在运行,只有当所有的非守护线程都结束的时候,虚拟机的进程才会结束,不管在运行的线程是不是main()线程。
3.Main主线程结束了(Non-daemon thread),如果此时正在运行的其他threads是daemon threads,JVM会使得这个threads停止,JVM也停下
  如果此时正在运行的其他threads有Non-daemon threads,那么必须等所有的Non daemon线程结束了,JVM才会停下来
4.总之,必须等所有的Non-daemon线程都运行结束了,只剩下daemon的时候,JVM才会停下来,注意Main主程序是Non-daemon 线程
  默认产生的线程全部是Non-daemon线程

class   A   implements   Runnable{ 
          public   void   run(){ 
                  for(;;){ 
                          System.out.println("Thread   A   run"); 
                  } 
          } 
  
          public   static   void   main(String[]   args){ 
                  System.out.println("Thread   main   started!"); 
                  try{ 
                          (new   Thread(new   A())).start(); 
                  }   catch   (Exception   e){ 
                  } 
                  System.out.println("Thread   main   ended!"); 
          } 
  };

会一直跑下去,因为main进程结束了,但   A   进程还没有结束,虚拟机不能退出, 
  
  class   A   implements   Runnable{ 
          public   void   run(){ 
                  for(;;){ 
                          System.out.println("Thread   A   run"); 
                  } 
          } 
  
          public   static   void   main(String[]   args){ 
                  System.out.println("Thread   main   started!"); 
                  try{ 
                          Thread   a   =   new   Thread(new   A()); 
                          a.setDaemon(true); 
                          a.start(); 
                  }   catch(Exception   e){ 
                  } 
                  System.out.println("Thread   main   ended!"); 
          } 
  }; 
  
  main   线程一退出,虚拟机就退出了,因为剩下在跑的   a   线程是守护线程,虚拟机不管它的死活的,直接退出了。

==============

http://www.linuxidc.com/Linux/2012-04/58858.htm

Java将线程分为User线程和Daemon线程两种。通常Daemon线程用来为User线程提供某些服务。程序的main()方法线程是一个User进程。User进程创建的进程为User进程。当所有的User线程结束后,JVM才会结束。

通过在一个线程对象上调用setDaemon(true),可以将user线程创建的线程明确地设置成Daemon线程。例如,时钟处理线程、idle线程、垃圾回收线程、屏幕更新线程等,都是Daemon线程。通常新创建的线程会从创建它的进程哪里继承daemon状态,除非明确地在线程对象上调用setDaemon方法来改变daemon状态。

需要注意的是,setDaemon()方法必须在调用线程的start()方法之前调用。一旦一个线程开始执行(如,调用了start()方法),它的daemon状态不能再修改。通过方法isDaemon()可以知道一个线程是否Daemon线程。

通过执行下面的代码,可以很清楚地说明daemon的作用。当设置线程t为Daemon线程时,只要User线程(main线程)一结束,程序立即退出,也就是说Daemon线程没有时间从10数到1。但是,如果将线程t设成非daemon,即User线程,则该线程可以完成自己的工作(从10数到1)。
1.import static java.util.concurrent.TimeUnit.*; 
2.public class DaemonTest { 
2.    public static void main(String[] args) throws InterruptedException {  3.        Runnable r = new Runnable() {  4.            public void run() {  5.                for (int time = 10; time > 0; --time) {  6.                    System.out.println("Time #" + time);  7.                    try {  8.                        SECONDS.sleep(2);  9.                    } catch (InterruptedException e) {  10.                        e.printStackTrace(); 
11.                    } 
12.                } 
13.            } 
14.        }; 
15.         
16.        Thread t = new Thread(r);  17.        t.setDaemon(true);  // try to set this to "false" and see what happens   18.        t.start(); 
19.         
20.        System.out.println("Main thread waiting...");  21.        SECONDS.sleep(6);  22.        System.out.println("Main thread exited.");  23.    } 
24.}

•t为Daemon线程的输出:
Time #10

Time #9

Time #8

Main thread exited.

Time #7

•t为User线程的输出:
Main thread waiting...

Time #10

Time #9

Time #8

Main thread exited.

Time #7

Time #6

Time #5

Time #4

Time #3

Time #2

Time #1

本篇文章来源于 Linux公社网站(www.linuxidc.com)  原文链接:http://www.linuxidc.com/Linux/2012-04/58858.htm

========http://javarevisited.blogspot.com/2012/03/what-is-daemon-thread-in-java-and.html

Friday, March 16, 2012

What is Daemon thread in Java and Difference to Non daemon thread - Tutorial Example

Daemon thread in Java are those thread which runs in background and mostly created by JVM for performing background task like Garbage collection and other house keeping tasks. Difference between Daemon and Non Daemon(User Threads)  is also an interesting multi-threading interview question, which asked mostly on fresher level java interviews. In one line main difference between daemon thread and user thread is that as soon as all user thread finish execuction java program or JVM terminates itself, JVM doesn't wait for daemon thread to finish there execution. As soon as last non daemon thread finished JVM terminates no matter how many Daemon thread exists or running inside JVM. In this java thread tutorial we will see example of Daemon thread in Java and some more differences between Daemon and non daemon threads.

Important points about Daemon threads in Java

1. 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).
2. 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.
3. Daemon Threads are suitable for doing background jobs like housekeeping, Though I have yet to use it for any practical purpose in application code. let us know if you have used daemon thread in your java application for any practical purpose.

Difference between Daemon and Non Daemon thread in Java

here are couple of differences between daemon and user thread in Java:
1) JVM doesn't wait for any daemon thread to finish before existing.
2) Daemon Thread are treated differently than User Thread when JVM terminates, finally blocks are not called, Stacks are not unwounded and JVM just exits.

Daemon Thread Example in Java

Here is a code example of daemon thread in java. we make a user thread daemon by calling setDaemon(true) and every time you run you will see variable number of print statement related to "daemon thread is running" you will never see print statement written in finally block because finally will not be called.
public class DaemonThreadExample {

public static void main(String args[]){
   
       Thread daemonThread = new Thread(new Runnable(){
            @Override
           public void
run(){
               try{
               while(true){
                   System.out.println("Daemon thread is running");
               }
                 
               }catch(Exception e){
                 
               }finally{
                   System.out.println("Daemon Thread exiting"); //never called
               }
           }
       }, "Daemon-Thread");
     
       daemonThread.setDaemon(true); //making this thread daemon
       daemonThread.start();
     
     
}

Output:
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running

That’s all on What is Daemon Thread in Java and difference between Deaemon and non deamon thread in Java with code example of Deamon thread in Java. JVM also uses deamon thread for Garbage collection.
Other Java tutorial on Threads you may like
How to Solve Producer Consumer Problem in Java
How to Stop Thread in Java
Why wait and notify methods are declared in Object Class?
Difference between Runnable and Thread in java
Why wait and notify needs to called from Synchronized Context?
Difference between invokeAndWait and InvokeLater in java Swing.
Difference between wait and sleep in Java
Difference between ConcurrentHashMap and Hashtable in Java
What is Race condition in java and how to deal with them
How to avoid deadlock in Java with code example
How to find if a thread holds lock in Java

Read more: http://javarevisited.blogspot.com/2012/03/what-is-daemon-thread-in-java-and.html#ixzz1t6oIGpg0

Java线程之守护线程(Daemon) .相关推荐

  1. Java线程之守护线程(Daemon)

    http://blog.csdn.net/mq612/article/details/1520571 守护线程(Daemon) Java有两种Thread:"守护线程Daemon" ...

  2. Java中的守护线程和非守护线程(转载)

    <什么是守护线程,什么是非守护线程> Java有两种Thread:"守护线程Daemon"(守护线程)与"用户线程User"(非守护线程). 用户线 ...

  3. Java多线程之守护线程实战

    转载自 Java多线程之<<守护线程>>实战 定义 什么是守护线程?与守护线程相对应的就是用户线程,守护线程就是守护用户线程,当用户线程全部执行完结束之后,守护线程才会跟着结束 ...

  4. (转)Java中的守护线程

    Java的守护线程与非守护线程 守护线程与非守护线程 最近在看多线程的Timer章节,发现运用到了守护线程,感觉Java的基础知识还是需要补充. Java分为两种线程:用户线程和守护线程 所谓守护线程 ...

  5. 额!Java中用户线程和守护线程区别这么大?

    作者 | 王磊 来源 | Java中文社群(ID:javacn666) 转载请联系授权(微信ID:GG_Stone) 在 Java 语言中线程分为两类:用户线程和守护线程,而二者之间的区别却鲜有人知, ...

  6. java并发:初探用户线程和守护线程

    用户线程和守护线程 用户线程 用户线程执行完,jvm退出.守护线程还是可以跑的 /*** A <i>thread</i> is a thread of execution in ...

  7. java中的守护线程

    在Java中有两类线程:User Thread(用户线程).Daemon Thread(守护线程) 用个比较通俗的比如,任何一个守护线程都是整个JVM中所有非守护线程的保姆: 只要当前JVM实例中尚存 ...

  8. JAVA守护线程 非守护线程

    笔记: 第一篇转载写的比较好,将守护线程同linux的守护进程概念进行了对比. 当非守护线程执行完jvm就退出,不管是否还有守护线程在执行.所以守护线程尽量不要执行逻辑代码,顶多执行一些可有可无的辅助 ...

  9. Java多线程之守护线程

    一.说明 Java中的线程分为两类:一种是守护线程,一种是用户线程.平台我们经常用到的就是用户线程.用户线程和守护线程,从本质上来说并没有什么区别,唯一的不同之处就在于虚拟机的离开:如果用户线程已经全 ...

最新文章

  1. opencv拟合高维曲线
  2. 高效开发:IntelliJ IDEA天天用,这些Debug技巧你都知道?
  3. 里氏替换原则→类型转换
  4. Spring三种对象创建方式
  5. java短除法获取二进制_Java十四天零基础入门-Java的数据类型介绍
  6. Windows Mobile 5.0新增API介绍(转自MSDN)
  7. SQL*Plus 系统变量之32 - NEWP[AGE]
  8. 面向对象的三大特性 - 继承、多态、封装
  9. 世界黑客编程大赛第一名的作品(97年Mekka ’97 4K Intro比赛)
  10. layui省市区联动选择的实现
  11. 【ENSP模拟器】RIP(HCNP)——RIPv2的配置及实现
  12. 李迟2022年4月工作生活总结
  13. 基于GAN的动漫头像生成
  14. 再爆hzhost6.5虚拟主机管理系统的SQL注入漏洞3
  15. 「大哉数学之为用」优选法——梯级水库灌溉的优化设计
  16. 中国/玩具鸭舰队/漂流15年 今夏将抵英国
  17. The first record --两次面试
  18. xlsx筛选近三年学计算机,计算机二级Office:Excel数据筛选和分类汇总
  19. 计算机电源接通显示未充电怎么办,win10已接通电源,但不显示充电怎么办_win10电脑电源接通但未充电是怎么回事...
  20. 双显卡双显示输出,怎么设置默认显卡为集显

热门文章

  1. Swift之源码编译的环境搭建和编译流程
  2. OpenGL之图元描边的绘制流程
  3. LeetCode SQL 196. 删除重复的电子邮箱
  4. 信息学奥赛一本通(C++)在线评测系统——基础(一)C++语言——1085:球弹跳高度的计算
  5. bashrc文件实例
  6. 【IT资讯】继哈工大Matlab软件被美禁用后,华为、360再遭Docker软件禁令
  7. 【Linux网络编程】IP 数据报格式详解
  8. 【Linux网络编程】TCP
  9. linux服务器备份软件下载,Linux服务器的常用备份方法 服务器系统备份方法
  10. 浙江省计算机网络技术比赛,[2018年最新整理]0509浙江省三级计算机网络技术历年真题(含答桉).doc...