[Guardian] Java threads (Daemon Thread)


I. Introduction


Threads can be divided into: ordinary thread and thread guard

The difference between an ordinary thread and thread guard that: the operation when the thread exits occurred.


(1) problem


1. When to use a daemon thread?

We want to create a thread to perform some auxiliary work, but do not want to close this thread hinder the JVM


2. What are the common thread guard there?

All threads created when the JVM starts, in addition to the main thread, other threads are daemon threads (eg, threads, and other garbage collector to perform auxiliary functions)


3. How to set up a daemon thread?

Thread.setDaemon(true);

By default, all the threads created by the main thread are common threads.


4. Why use a small daemon thread?

When a thread exits, JVM will check other threads running, if these threads are daemon threads, the JVM will exit normally operate.

When the JVM is stopped, all remains the guardian of the thread will be abandoned - neither execute finallya block of code, it will not perform stack unwinding, but only JVM to exit.

With as little as a daemon thread, because few operations can be safely discarded without liquidating.

In addition, the daemon thread usually can not be used to replace the application lifecycle management process for each service.

So, when a thread is created, we need to consider the situation to clean up, after the abnormal clear.



Second, the case


public class DaemonDemo {

    public static class DaemonT extends Thread {
        public void run() {
            while (true) {
                System.out.println("I am alive");

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t = new DaemonT();
        t.setDaemon(true);
        t.start();
        Thread.sleep(2000);
    }
}

Output:

I am alive
I am alive
I am alive

// Process finished with exit code 0

If not set t.setDaemon(true);, that is not set to the user thread, t thread will run next.

Published 404 original articles · won praise 270 · views 420 000 +

Guess you like

Origin blog.csdn.net/fanfan4569/article/details/102005871