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

difference between daemon and non daemon thread in java example 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



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

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐