Multithreading learning note 03 thread status

Multithreading learning note 03 thread status

brief introduction

  1. Creation status: Thread t = new Thread() once the thread object is created, it enters the new state;
  2. Ready state: when the start() method is called, the thread immediately enters the ready state, but it does not mean that the execution is scheduled immediately;
  3. Running state: when the thread enters the running state, the thread really executes the code block of the thread body;
  4. Blocking state: when calling sleep, wait or synchronous locking, the thread enters the blocking state, that is, the code does not execute down. After the blocking event is released, it enters the ready state again and waits for the cpu to schedule and execute;
  5. Dead state: the thread is interrupted or terminated. Once it enters the dead state, it cannot be started again.

Thread method

methodexplain
setPriority(int newPriority)Change the priority of a thread
static void sleep(long millis)Hibernate the currently executing thread body within the specified number of milliseconds
void join()Wait for the thread to terminate
static void yield()Pauses the currently executing thread object and executes other threads
void interrupt()Interrupt thread (not recommended)
boolean isAlive()Test whether the thread is active

Thread stop

  • The stop()\destroy() method provided by JDK is not recommended. (abandoned)
  • It is recommended that the thread stop by itself
  • It is recommended to use a flag bit to terminate the variable. When flag=false, the thread will be terminated.
public class TestStop implements Runnable {

    //1. Set a flag bit
    private boolean flag = true;

    @Override
    public void run() {
        int i = 0;
        while (flag) {
            System.out.println("run...Thread" + i++);
        }
    }

    //2. Set a public method to stop the thread and convert the flag bit
    public void stop() {
        this.flag = false;
    }

    public static void main(String[] args) {
        TestStop testStop = new TestStop();

        new Thread(testStop).start();

        for (int i = 0; i < 1000; i++) {
            System.out.println("main" + i);
            if (i == 900) {
                //Call the stop method to switch the flag bit and stop the thread
                testStop.stop();
                System.out.println("It's time for the thread to stop");
            }

        }
    }
}

Operation results:

Thread sleep

  • sleep specifies the number of milliseconds that the current thread is blocked;
  • There is an exception InterruptedException in sleep;
  • After the sleep time reaches, the thread enters the ready state;
  • sleep can simulate network delay, countdown, etc.
  • Every object has a lock, and sleep will not release the lock.

Analog Countdown:

//Analog countdown
public class TestSleep {

    public static void main(String[] args) {
        try {
            tenDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void tenDown() throws InterruptedException {
        int num = 10;

        while (true) {
            Thread.sleep(1000);
            System.out.println(num--);
            if (num <= 0) {
                break;
            }
        }
    }
}

Operation results:

Thread comity

  • Comity thread: pause the currently executing thread without blocking;
  • Change the thread from running state to ready state;
  • Let the CPU reschedule. Comity is not necessarily successful. It depends on the CPU mood.
//Thread comity
public class TestYield {

    public static void main(String[] args) {
        MyYield myYield = new MyYield();
        new Thread(myYield, "a").start();
        new Thread(myYield, "b").start();
    }
}

class MyYield implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "The thread starts executing");
        Thread.yield();//Comity
        System.out.println(Thread.currentThread().getName() + "Thread stop execution");
    }
}

Operation results:

Comity success!

Thread enforcement (join)

  • join merge threads. After this thread is completed, execute other threads. Other threads are blocked
  • Imagine jumping in line
//join method
public class TestJoin implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("thread  vip coming" + i);
        }
    }

    public static void main(String[] args) throws InterruptedException {

        //Start thread
        TestJoin testJoin = new TestJoin();
        Thread thread = new Thread(testJoin);

        //Main thread
        for (int i = 0; i < 500; i++) {
            if (i == 200) {
                thread.start();
                thread.join();//Jump in line
            }
            System.out.println("main" + i);
        }
    }
}

Operation results:

Thread state observation

Thread.State
Thread state. A thread can be in one of the following states:

  • NEW
    Threads that have not been started are in this state
  • RUNNABLE
    The thread executing in the Java virtual machine is in this state
  • BLOCKED
    Threads that are blocked waiting for a monitor lock are in this state
  • WAITING
    The thread that is waiting for another thread to perform the action for the specified waiting time is in this state
  • TIMED_WAITING
    The thread that is waiting for another thread to perform the action for the specified waiting time is in this state
  • TERMINATED
    The exited thread is in this state

A thread can be in a state at a given point in time. These states are virtual machine states that do not reflect the state of any operating system thread.

//Observe the status of the test thread
public class TestState {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("......");
        });

        //Observation state
        Thread.State state = thread.getState();
        System.out.println(state);

        //Observe after startup
        thread.start();
        state = thread.getState();
        System.out.println(state);//Run

        while (state != Thread.State.TERMINATED) {
            //As long as the thread does not terminate, it will always output the state
            Thread.sleep(100);
            state = thread.getState();//Update thread status
            System.out.println(state);//Output status
        }
    }
}


thread priority

  • Java provides a thread scheduler to monitor all threads that enter the ready state after startup. The thread scheduler determines which thread should be called to execute according to priority.
  • The priority of threads is expressed in numbers, ranging from 1 to 10
    Thread.MIN_PRIORITY =1;
    Thread.MAX_PRIORITY =10;
    Thread.NORM_PRIORITY = 5;
  • Change or obtain priorities in the following ways
    getPriority() . setPriority(int xxx)
//Test thread priority
public class TestPriority {
    public static void main(String[] args) {
        //Default priority of main thread
        System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());

        MyPriority myPriority = new MyPriority();

        Thread t1 = new Thread(myPriority);
        Thread t2 = new Thread(myPriority);
        Thread t3 = new Thread(myPriority);
        Thread t4 = new Thread(myPriority);
        Thread t5 = new Thread(myPriority);

        //Set priority before starting
        t1.start();//Default Priority 

        t2.setPriority(1);
        t2.start();

        t3.setPriority(4);
        t3.start();

        t4.setPriority(Thread.MAX_PRIORITY);//Highest priority
        t4.start();

        t5.setPriority(2);
        t5.start();


    }

}

class MyPriority implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
    }
}

Low priority only means that the probability of obtaining scheduling is low, not that it will not be called if the priority is low, which depends on the scheduling of CPU

Daemon thread

  • Threads are divided into user threads and daemon threads
  • The virtual machine must ensure that the user thread has completed execution
  • The virtual machine does not have to wait for the daemon thread to finish executing
  • For example, recording operation logs in the background, monitoring memory, garbage collection and waiting

Keywords: Java Back-end

Added by ccravens on Wed, 02 Feb 2022 20:41:38 +0200