[JavaSE] Multi-threading (3) User threads, daemon threads and seven major states of threads

💁 Homepage:Huang Xiaohuang’s blog homepage
❤️ support me: Like, collect and follow
🎏 motto:All miracles start from sometime somewhere, make it right now.
This article comes from the column:JavaSE from entry to proficiency


1 User thread and daemon thread

  1. User thread:User threads are also called worker threads. When the thread’s task is completed or terminated by notification.
  2. Daemon thread:Generally it serves worker threads. When all user threads end, the daemon thread ends automatically. The garbage collection mechanism is a common daemon thread.

🐱 Why do we need daemon threads?

By default, when the main thread main starts a sub-thread t, when the main thread ends, it does not affect the execution of the sub-thread t. However, in some cases, we hope that when the main thread or user thread ends, the sub-thread t will automatically end, so there is a daemon thread.


2 How to set a thread as a daemon thread?

🐘 illustrate:

  • If you want to set a thread as a daemon thread, thenJust use the setDeamon() method of the thread and set the parameter to true;
  • have to be aware of is,The thread must be set as a daemon thread before starting the thread.Otherwise an exception will be thrown.

🐰 The case is as follows:

In this case, the thread T is set as a daemon thread, which realizes the requirement that the T thread automatically ends when the main thread ends.

/**
 * @author Huang Xiaohuang due to interest
 * @version 1.0
 *Daemon thread case demonstration
 */
public class ProtectedThreadTest {

    public static void main(String[] args) throws InterruptedException {
        T t = new T();
        //Set t as a daemon thread
        t.setDaemon(true);
        t.start();
        //The main thread stops after executing 3 times
        for (int i = 1; i <= 3; i++) {
            System.out.println("Thread main is executing...");
            Thread.sleep(1000);
        }
        System.out.println("==============Ended main thread!!==============");
    }
}

class T extends  Thread{

    @Override
    public void run() {
        for (;;){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread T is executing...");
        }
    }
}


3 The 7 major states of threads

3.1 Why do we say 7 majors instead of 6 majors?

In fact, it is used in the official documentation and JDKThread.StateThe enumeration representsThe six major states of threads,details as follows:

  • NEW (initial state):Threads that have not yet been started are in this state;
  • RUNNABLE (runnable state):Threads executing in the Java virtual machine are in this state;
  • BLOCKED (blocked state):A thread blocked waiting for a monitor lock is in this state;
  • WAITING (waiting state):A thread that is waiting for another thread to perform a specific action is in this state;
  • TIMTED_WAITING (timeout waiting state):A thread that is waiting for another thread to perform an action for a specified waiting time is in this state;
  • TERMINATED:A thread that has exited is in this state.

So why are there 7 major states?Let’s take a look at the thread state diagram:

When the thread uses the start method, it will change from the NEW initial state to the RUNNABLE runnable state. inThe runnable state can be divided into: Ready state and Running state.
In other words, after refinement, a total of threads have 7 major states. What we need to be clear about is,Runnable represents the runnable state and does not necessarily run immediately. Its ready state and running state depend on the system kernel. Running really takes up the CPU.
The thread concession we learned in the previous section uses the yield method. The reason why it may not be successful is that the thread is only placed in the Ready state.

3.3 Check the status of the thread through the program

/**
 * @author Huang Xiaohuang due to interest
 * @version 1.0
 */
public class ThreadStateTest {
    public static void main(String[] args) throws InterruptedException {
        ThreadForMe threadForMe = new ThreadForMe();
        System.out.println(threadForMe.getName() + "status" + threadForMe.getState());
        threadForMe.start();
        // As long as threadForMe is not terminated, keep checking the status
        while (Thread.State.TERMINATED != threadForMe.getState()){
            System.out.println(threadForMe.getName() + "status" + threadForMe.getState());
            Thread.sleep(1000);
        }
        System.out.println(threadForMe.getName() + "status" + threadForMe.getState());
    }
}

class ThreadForMe extends Thread{
    @Override
    public void run() {
        while (true){
            for (int i = 1; i <= 10; i++) {
                System.out.println("hi" + i);
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


write at the end

The above is the entire content of this article, and the follow-up content will continueFree updates, if the article is helpful to you, please give me a handLike + follow,Thank you so much !
If you have any questions, please leave a private message or comment section!

Encourage each other: “Your intermittent efforts and muddled living are all a cleansing of your previous efforts.”

Related Posts

From shallow to deep, I will take you through the three ways to implement array expansion in Java [recommended collection]

Java connects to the database to implement basic additions, deletions, modifications and queries

When adding dependencies to pom files, an unknown problem occurs [maven]. A complete solution to dependency error reporting in maven projects.

A simple tutorial on how to use the MybatisX plug-in in SpringBoot (super detailed!!)

Windows 11 configure JDK environment variables

In the 2022 1024 card event, how do programmers judge whether their cards can form 1024? Then have fun programming it︕

append() method in JAVA

[ElasticSearch Series 6] Use QueryBuilders and NativeSearchQuery to implement various operations of es database on lists {multiple conditions, paging, sorting, highlighting (with highlighting tool class), etc.}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*