Multi-threaded study notes (3)--user thread and daemon thread

expound

There are two kinds of threads in Java thread: ① user thread ② daemon thread

User thread: The common threads that are usually used are user threads

Daemon thread: refers to a thread that provides a general service in the background when the program is running. The daemon thread serves the user thread. When a user thread is running, the daemon thread also needs to work. When all user threads are finished , the daemon thread will also stop

How to use the daemon thread

  • Set the thread's Daemon to true, and must be set before thread.start()
  • The new thread spawned in the Daemon thread is also a Daemon
  • The daemon thread should not access inherent resources, such as read and write operations (files, databases), because the daemon thread follows the user thread, and when there is no user thread to work, the daemon thread will end immediately

Example

  • When there is no daemon thread
public class Daemon {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }
                System.out.println("Daemon thread end...");
            }
        });
//        thread.setDaemon(true);    //①
        thread.start();
        System.out.println("User thread ends...");
    }
}

operation result:

Prove that when all user threads end, the daemon thread can still execute


  • When there is a daemon thread
public class Daemon {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }
                System.out.println("Daemon thread end...");
            }
        });
        thread.setDaemon(true);    //①
        thread.start();
        System.out.println("User thread ends...");
    }
}

operation result:

When all user threads end, the daemon thread ends and will not continue to execute


Application scenarios of daemon thread

  • Not suitable for I/O or computational operations
  • Suitable for auxiliary user thread scenarios, such as GC, memory management

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325935540&siteId=291194637