In the Java language, there are two types of threads: user threads and daemon threads. By default, any thread or thread pool we create is a user thread, so user threads are also called normal threads.

To check whether a Thread is a user Thread or a daemon Thread, use thread.isdaemon () to determine whether it is a daemon Thread if it returns true or a user Thread if it is not.

Let’s test what thread types are threads and thread pools by default? The test code is as follows:

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/** * Thread type: daemon thread OR user thread */
public class ThreadType {
    public static void main(String[] args) {
        // Create a thread
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run(a) {
                / /...}});// Create a thread pool
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10.10.0, TimeUnit.SECONDS, new LinkedBlockingQueue<>(100));
        threadPool.submit(new Runnable() {
            @Override
            public void run(a) {
                System.out.println(ThreadPool thread type: +
                        (Thread.currentThread().isDaemon() == true ? "Daemon thread" : "User thread")); }}); System.out.println("Thread 线程类型:" +
                (thread.isDaemon() == true ? "Daemon thread" : "User thread"));
        System.out.println("Main Thread type:" +
                (Thread.currentThread().isDaemon() == true ? "Daemon thread" : "User thread")); }}Copy the code

The execution result of the above program is as follows:As you can see from the above results, both threads and thread pools created by default are user threads.

Daemon thread definition

Daemon threads are also known as background threads or server threads. They serve user threads and end when all user threads finish executing. The role of the daemon thread is like “waiter”, and the role of the user thread is like “customer”. When all the “customers” are gone (all execution is finished), the “waiter” (daemon thread) also has no meaning. Therefore, when all user threads in a program have finished execution, Whether the daemon thread is still working or not ends with the user thread, and the entire program ends with it.

Creating a daemon thread

We can set threads to be daemons with the thread.setdaemon (true) method, as in the following code:

public static void main(String[] args) {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run(a) {
            / /...}});// Set the thread to a daemon thread
    thread.setDaemon(true);
    System.out.println("Thread 线程类型:" +
                       (thread.isDaemon() == true ? "Daemon thread" : "User thread"));
    System.out.println("Main Thread type:" +
                       (Thread.currentThread().isDaemon() == true ? "Daemon thread" : "User thread"));
}
Copy the code

The execution result of the above program is as follows:

Set the thread pool as a daemon thread

Setting the pool to daemons is a bit more complicated, requiring all threads in the pool to be daemons. In this case, you need to use a ThreadFactory ThreadFactory to set the pool to daemons.

public static void main(String[] args) throws InterruptedException {
    // Thread factory (set daemon thread)
    ThreadFactory threadFactory = new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            // Set to daemon thread
            thread.setDaemon(true);
            returnthread; }};// Create a thread pool
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10.10.0, TimeUnit.SECONDS, new LinkedBlockingQueue<>(100), threadFactory);
    threadPool.submit(new Runnable() {
        @Override
        public void run(a) {
            System.out.println(ThreadPool thread type: +
                               (Thread.currentThread().isDaemon() == true ? "Daemon thread" : "User thread")); }}); Thread.sleep(2000);
}
Copy the code

The execution result of the above program is as follows:

Daemon threads vs. user threads

Now that we know what a user thread is and what a daemon thread is, what’s the difference? Let’s take a look at this with a small example. Next, we will create a thread, set this thread as user thread and daemon thread respectively, and execute a for loop in each thread, printing the information 10 times in total, sleeping 100 milliseconds after each printing to observe the results of the program.

User threads

The new thread is the user thread by default, so we do not need to do any special processing for the thread, we can execute the for loop (a total of 10 times to print information, after each print 100 milliseconds sleep), implementation code is as follows:

public static void main(String[] args) throws InterruptedException {
    // Create a user thread
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run(a) {
            for (int i = 1; i <= 10; i++) {
                // Prints I information
                System.out.println("i:" + i);
                try {
                    // Hibernate for 100 milliseconds
                    Thread.sleep(100);
                } catch(InterruptedException e) { e.printStackTrace(); }}}});// Start the thread
    thread.start();
}
Copy the code

The execution result of the above program is as follows:As you can see from the above results, the process does not end normally until the program has finished printing 10 times.

Daemon thread

public static void main(String[] args) throws InterruptedException {
    // Create a daemon thread
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run(a) {
            for (int i = 1; i <= 10; i++) {
                // Prints I information
                System.out.println("i:" + i);
                try {
                    // Hibernate for 100 milliseconds
                    Thread.sleep(100);
                } catch(InterruptedException e) { e.printStackTrace(); }}}});// Set to daemon thread
    thread.setDaemon(true);
    // Start the thread
    thread.start();
}
Copy the code

The execution results of the above programs are shown below:When the thread is set to daemon, the program does not wait for the daemon to loop for 10 times before closing. Instead, when the main thread ends, the daemon ends without executing a single loop, which shows the difference between daemon and user threads.

Daemon thread considerations

SetDaemon (true) must be set before start(), otherwise the program will report an error. This means that the type of the thread must be determined before it is run, and it is not allowed to change the type of the thread after it is run. Let’s show what happens if we set the thread type while the program is running. The demo code is as follows:

public static void main(String[] args) throws InterruptedException {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run(a) {
            for (int i = 1; i <= 10; i++) {
                // Prints I information
                System.out.println("i:" + i + ",isDaemon:" +
                            Thread.currentThread().isDaemon());
                try {
                    // Hibernate for 100 milliseconds
                    Thread.sleep(100);
                } catch(InterruptedException e) { e.printStackTrace(); }}}});// Start the thread
    thread.start();
    // Set to daemon thread
    thread.setDaemon(true);
}
Copy the code

The execution results of the above programs are shown below:We can see from the above results that when setDaemon(true) is set after start(), not only does the program execute with an error, but the setDaemon thread does not take effect.

conclusion

Threads in the Java language fall into two categories: User threads and daemons, by default, the threads or thread pools that we create are user threads, daemons serve user threads, and when all user threads in an application are finished executing, the application ends running, it doesn’t care if the daemons are running, From this we can see that daemon threads have a low weight in the Java architecture, which is the difference between daemon threads and user threads.

Judge right and wrong from yourself, praise to listen to others, gain and loss in the number.

Public number: Java interview analysis

Interview collection: gitee.com/mydb/interv…