Daemon threads and non-daemon threads

What is a daemon thread

As mentioned in previous articles, there are two types of threads in Java: User threads and daemons.

There is little difference between the user thread and the daemon thread, except that the virtual machine exits: if the user thread exits completely and only the daemon thread remains, the virtual machine exits.

The most classic use of daemon threads is the thread responsible for GC. As long as the user thread is there, he takes his job seriously.

How do I create a daemon thread

Converting a Thread to a daemon can be done by calling the setDaemon(true) method on the Thread object. A few things to note when using daemons:

(1) thread. SetDaemon (true) must be in the thread. The start () set before, otherwise you will run out of a IllegalThreadStateException anomalies. You cannot set a running regular thread as a daemon thread.

public class Test {
    public static void main(String[] args) {
        Thread t = new Thread(()->{
            while(true){
                System.out.println("I'm the daemon thread T, I'm running."); }}); t.setDaemon(true);
        t.start();
// try {
// TimeUnit.SECONDS.sleep(1);
// } catch (InterruptedException e) {
// e.printStackTrace();
/ /}}}// This will print nothing, but if you remove the comment and stop the main thread for a second it will print.
Copy the code

(2) A new thread created in a daemon thread is also a daemon thread.

public class Test {
    public static void main(String[] args) {
        Thread t = new Thread(()->{
            Thread a = new Thread(()->{
                while (true){
                    System.out.println("I'm thread A, I'm running."); }}); a.start(); }); t.setDaemon(true);
        t.start();
// try {
// TimeUnit.SECONDS.sleep(1);
// } catch (InterruptedException e) {
// e.printStackTrace();
/ /}}}// This will print nothing, but if you remove the comment and stop the main thread for a second it will print. This proves that A is also the daemon thread
Copy the code

(3) Daemon threads should never access inherent resources, such as files or databases, because it can break at any time or even in the middle of an operation.

In addition, IsDaemon() on the Thread object is called to see if the object is a daemon thread.

public static void main(String[] args) {
    Thread t = new Thread(()->{
        Thread a = new Thread(()->{
            while (true) {// system.out.println (" I'm thread A, I'm running ");}}); System.out.println(a.isDaemon()); a.setDaemon(false);
        System.out.println(a.isDaemon());
        a.start();
    });
    t.setDaemon(true);
    t.start();
    try {
        TimeUnit.MILLISECONDS.sleep(200);
    } catch(InterruptedException e) { e.printStackTrace(); }}// Prints true and false. A can run forever
Copy the code

However, I have never used daemons in my business, so I think it is a good point to know.