What is a daemon thread in Java?

任何人都可以告诉我Java中的守护线程是什么?


A daemon thread is a thread that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection.

You can use the setDaemon(boolean) method to change the Thread daemon properties before the thread starts.


A few more points (Reference: Java Concurrency in Practice)

  • When a new thread is created it inherits the daemon status of its parent.
  • Normal thread and daemon threads differ in what happens when they exit. When the JVM halts any remaining daemon threads are abandoned:

  • finally blocks are not executed,
  • stacks are not unwound - the JVM just exits.

  • Due to this reason daemon threads should be used sparingly and it is dangerous to use them for tasks that might perform any sort of I/O.


    All the above answers are good. Here's a simple little code snippet, to illustrate the difference. Try it with each of the values of true and false in setDaemon .

    public class DaemonTest {
    
        public static void main(String[] args) {
            new WorkerThread().start();
    
            try {
                Thread.sleep(7500);
            } catch (InterruptedException e) {
                // handle here exception
            }
    
            System.out.println("Main Thread ending") ;
        }
    
    }
    
    class WorkerThread extends Thread {
    
        public WorkerThread() {
            // When false, (i.e. when it's a user thread),
            // the Worker thread continues to run.
            // When true, (i.e. when it's a daemon thread),
            // the Worker thread terminates when the main 
            // thread terminates.
            setDaemon(true); 
        }
    
        public void run() {
            int count = 0;
    
            while (true) {
                System.out.println("Hello from Worker "+count++);
    
                try {
                    sleep(5000);
                } catch (InterruptedException e) {
                    // handle exception here
                }
            }
        }
    }
    
    链接地址: http://www.djcxy.com/p/41804.html

    上一篇: Java的重入锁定和死锁

    下一篇: Java中的守护进程是什么?